[英]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.