簡體   English   中英

使用重繪和計時器每秒旋轉一行

[英]Rotating a line every second using repaint and a timer

因此,我嘗試使用計時器和繪畫方法每秒旋轉一條線。 但是,我不太確定發生了什么。 以下是一些相關方法:

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方法,命令行每秒發出“滴答聲” 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() 有關揮桿定制繪畫的更多信息,請點擊此處。

編輯:現在有更多代碼可用,可以說,如果將時鍾和動作偵聽器設為靜態,則它應該可以工作。 但是 ,您需要在相關組件准備就緒后啟動計時器:

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();
        }
    });
}

關於在動作監聽器中創建時鍾的上述要點仍然存在。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM