[英]How do you delay a program when you click a button (java swing)
I am creating a program with a jbutton
and a jtextfield
.我正在创建一个带有
jbutton
和jtextfield
的程序。 I want the textfield to display a message and then make the whole frame disappear after 1 second.我希望文本字段显示一条消息,然后在 1 秒后使整个帧消失。 I was able to display the message and make the frame disappear using
frame.dispose
but I can't see the message because the frame disappears instantly.我能够使用
frame.dispose
显示消息并使框架消失,但我看不到消息,因为框架立即消失。 This is what I've tried.这是我尝试过的。 I heard using the swing timer also works but I have no idea how to use the swing timer.
我听说使用 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();
}
}
}
First is to create a subclass of TimerTask and override the run method.首先是创建 TimerTask 的子类并覆盖 run 方法。 Then, set the Timer to run this after the set amount of time.
然后,将计时器设置为在设定的时间后运行。
class Dispose extends TimerTask {
@Override
public void run() {
frame.dispose;
}
}
then...然后...
new Timer().schedule(new Dispose(), 1000);
The timer object will dispose the frame after 1000 milliseconds (1s)定时器 object 将在 1000 毫秒 (1s) 后处理帧
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.