[英]How do you delay a program when you click a button (java swing)
我正在创建一个带有jbutton
和jtextfield
的程序。 我希望文本字段显示一条消息,然后在 1 秒后使整个帧消失。 我能够使用frame.dispose
显示消息并使框架消失,但我看不到消息,因为框架立即消失。 这是我尝试过的。 我听说使用 swing 定时器也可以,但我不知道如何使用 swing 定时器。
//imports
public class GUIFastCash {
JFrame frame;
static JTextField window;
JButton twenty;
public void go () {
window = new JTextField();
twenty = new JButton("$20");
twenty.addActionListener(new Twenty());
frame = new JFrame();
//code adding button and textfield to frame
}
class Twenty implements ActionListener {
public void actionPerformed (ActionEvent event) {
//code to execute
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
frame.dispose();
}
}
}
首先是创建 TimerTask 的子类并覆盖 run 方法。 然后,将计时器设置为在设定的时间后运行。
class Dispose extends TimerTask {
@Override
public void run() {
frame.dispose;
}
}
然后...
new Timer().schedule(new Dispose(), 1000);
定时器 object 将在 1000 毫秒 (1s) 后处理帧
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.