java - 使用重绘和计时器每秒旋转一条线

标签 java swing timer paint repaint

所以我尝试使用计时器和绘制方法每秒旋转一条线。但是,我不太确定发生了什么事。以下是一些相关方法:

public static ActionListener taskPerformer = new ActionListener() {

    public void actionPerformed(ActionEvent e) {
        Clock cl = new Clock();
        seconds++;
        cl.repaint();
    }
};


public void paint(Graphics g){
    super.paint(g);
    Graphics2D g2 = (Graphics2D) g;
    for(int c = 0; c<10; c++){
        g2.setPaint(Color.BLACK);
        g2.drawOval(90-c/2,90-c/2,500+c,500+c); //thick outlined circle
    }
    g2.setPaint(Color.WHITE);
    g2.fillOval(90,90,501,501);
    g2.setPaint(Color.BLACK);
    g2.rotate(Math.toRadians(seconds*6));
    g2.drawLine(340,340,340,90);    

}

线路保持静止。但是如果我添加

System.out.println("tick");

对于我的 actionPerformed 方法,命令行每秒输出“tick”3 次。关于为什么会发生这些事情有什么想法吗?

一些背景:

public static int seconds = 0;
public static int minutes = 0;
public static int hours = 0;
public static Clock cl = new Clock();
private ActionListener taskPerformer = new ActionListener() {

    public void actionPerformed(ActionEvent e) {
        System.out.println("tick");
        seconds++;
        cl.repaint();
    }
};
public static Timer timer = new Timer(1000,taskPerformer);

public static void main(String[] args){
    Clock cl = new Clock();
    init();
    SwingUtilities.invokeLater(new Runnable(){
        public void run() {
            createAndShowGUI();
        }
    });
}
public static void init(){
    timer.start();
}
public Clock() {
    super("Clock");
    timer.addActionListener(taskPerformer);

}

最佳答案

您在每个时钟周期创建一个新时钟:

public void actionPerformed(ActionEvent e) {
    Clock cl = new Clock();
    ...

您应该使用现有实例。

// A field in the class:
Clock cl = new Clock();
...

// removed static so that it can access cl
private ActionListener taskPerformer = new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        seconds++;
        cl.repaint();
    }
};

如果您不需要在其他地方访问时钟,您还可以将时钟作为操作监听器中的一个字段。

另请注意,您通常不应重写 paint(),而应重写 paintComponent()。有关 Swing 中自定义绘画的更多信息 here.

编辑: 现在有了更多可用代码,可以说,如果将时钟和操作监听器设为静态,它应该可以工作。 但是,您需要在相关组件准备好后启动计时器:

public static void main(String[] args){
    // Removed spurious clock here
    SwingUtilities.invokeLater(new Runnable(){
        public void run() {
            createAndShowGUI();
            // Start the timer once the components are ready
            init();
        }
    });
}

上面提到的关于在 Action 监听器中创建时钟的观点仍然成立。

关于java - 使用重绘和计时器每秒旋转一条线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18815260/

相关文章:

javascript - 如何反转计数并设置倒计时开始时间?

java - 如何在 Mac OS X 10.9 上加速 IntelliJ

java - 两个 JPanel 之间的水平粘合未按预期发挥作用

java - 带有单元格闪烁的 JTable

java - 从查询中填充 Jtable

java - setPreferredSize 不起作用

java - 显示倒计时并在倒计时结束时更改为另一个 Activity 。

java - 在 Java 中使未处理的异常破坏程序

java - 使用 JOAuth 库在 LinkedIn 中发布职位

java - Android Studio 错误 - 不可转换的类型,无法转换 fragment