我正試圖創建一個應用程序,並且我想添加一個時鐘。我正在使用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())));
}
嵌套類或匿名類的確是要走的路 – Robin