2012-05-31 43 views
0

我正試圖創建一個應用程序,並且我想添加一個時鐘。我正在使用JPanel和ActionListener製作時鐘,並且還想使用Timer。 Swing教程說,要實例化一個Timer,你會說新的Timer(numMillis,this(一個ActionListener)),但是,「this」似乎不適用於JPanel項目。 什麼我會添加到Timer構造函數來正確實例化Timer?JPanel中的計時器

public ClockPanel() { 
    super(); 

    clockLabel.setText(sdf.format(new Date(System.currentTimeMillis()))); 
    clockLabel.setFont(new Font("Monospaced", Font.BOLD, 100)); 
    clockLabel.setOpaque(true); 
    clockLabel.setBackground(Color.black); 
    clockLabel.setForeground(Color.white); 

    timer = new Timer(500, this); 
    timer.setRepeats(true); 
    timer.start(); 

    clockLabel.setVisible(true); 

    initComponents(); 
} 
public void actionPerformed(ActionEvent e){ 
    if(e.getSource().equals(timer)) 
     clockLabel.setText(sdf.format(new Date(System.currentTimeMillis()))); 
    } 

回答

1

我假設你ClockPanel樣子:

public class ClockPanel extends JPanel implements ActionListener { 

你的行動執行似乎正常工作。如果您在設置文本之前進行了打印,您將看到它正在被調用。也許你沒有刷新文本更新後的屏幕,這就是爲什麼你沒有看到變化。

3

要避免leaking this,您可以使用實現ActionListener的嵌套類,如此example中所示。

+2

嵌套類或匿名類的確是要走的路 – Robin