如何在完成30秒的持续时间内通过代码关闭计时器窗口。
这是我的代码
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import java.util.Date;
class CountdownTimer extends JFrame {
private static final long serialVersionUID = -3613327984360590187L;
public CountdownTimer() {
setTitle("Countdown Timer");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final long MINUTES = 30000;
final SimpleDateFormat sdf = new SimpleDateFormat("mm : ss");
final JLabel clock = new JLabel(sdf.format(new Date(MINUTES)), JLabel.CENTER);
JLabel text = new JLabel("Time Remaining: ");
int x = 0;
ActionListener actionListener = new ActionListener() {
long x = MINUTES - 1000;
public void actionPerformed(ActionEvent ae) {
clock.setText(sdf.format(new Date(x)));
x -= 1000;
}
};
new javax.swing.Timer(1000, actionListener).start();
JPanel jPanel = new JPanel();
jPanel.add(text);
jPanel.add(clock);
getContentPane().add(jPanel);
pack();
}
public static void main(String args[]) {
new CountdownTimer().setVisible(true);
}
}
如何在完成30秒的持续时间内通过代码关闭计时器窗口。
这是我的代码
答案 0 :(得分:2)
this.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));
答案 1 :(得分:2)
试试这个:
public void actionPerformed(ActionEvent ae) {
clock.setText(sdf.format(new Date(x)));
x -= 1000;
if (x < 0) // Add this line
CountdownTimer.this.dispose(); // And this one too
}