您必須實現WindowStateListener或WindowListener。如果您使用的WindowListener它可能看起來像這樣:
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.Timer;
public class Foo implements WindowListener {
private Timer timer;
public static void main(String args[]){
initTimerComponent();
}
private void initTimerComponent() {
int delay = 1000; //milliseconds
timer = new Timer(delay, null);
timer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
tempLabel.setVisible(true);
String tmp = "test";
tempLabel.setText("Temperature : " + tmp);
}
});
timer.start();
}
@Override
public void windowOpened(WindowEvent e) { }
@Override
public void windowClosing(WindowEvent e) {
timer.stop();
}
@Override
public void windowClosed(WindowEvent e) { }
@Override
public void windowIconified(WindowEvent e) { }
@Override
public void windowDeiconified(WindowEvent e) { }
@Override
public void windowActivated(WindowEvent e) { }
@Override
public void windowDeactivated(WindowEvent e) { }
}
您必須實現所有這些作爲的WindowListener是一個接口,實現接口的第一個具體類是被迫實施其所有的抽象方法。但你實際上只需要一種方法。
使用此方法
public void windowClosing(WindowEvent e) {
timer.stop();
}
儘快停止你的定時器的窗口正在關閉用戶點擊紅色的X後
看到的WindowStateListener – ControlAltDel
@ControlAltDel你可以修改我的代碼,並告訴我如何請使用它? – fredjohnson
@fredjohnson,搜索論壇的例子。您現在知道要搜索的類名稱。 – camickr