当用户点击JFrame的红色“X”按钮时,如何检测JFrame是打开还是关闭?我有一个摆动计时器,JFrame不断更新它的标签,直到用户关闭JFrame。
int delay = 1000; //milliseconds
final Timer 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.stop();
}
});
timer.start();
答案 0 :(得分:1)
您必须实现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后,在窗口关闭后立即停止计时器。
答案 1 :(得分:0)
回答
addWindowListener(new WindowAdapter() {
//for closing
@Override
public void windowClosing(WindowEvent e) {
JOptionPane.showMessageDialog(null, "Closing");
}
//for closed
@Override
public void windowClosed(WindowEvent e) {
}
});