java - 单击按钮时如何延迟程序(java swing)
问题描述
我正在创建一个带有 ajbutton
和 a的程序jtextfield
。我希望文本字段显示一条消息,然后在 1 秒后使整个帧消失。我能够显示消息并使框架消失,frame.dispose
但我看不到消息,因为框架立即消失。这是我尝试过的。我听说使用摇摆定时器也可以,但我不知道如何使用摇摆定时器。
//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);
计时器对象将在 1000 毫秒 (1s) 后处理帧
推荐阅读
- xamarin - Android 设备中不存在 UI 推送通知 - Xamarin Plugin.FirebasePushNotification
- c++ - vector::emplace_back 结果调用析构函数两次
- fiddler - 为什么 Fiddler4 不支持 Content-Type 'application/x-protobuf'?
- excel - 如何在不使用 VBA 的情况下过滤 excel 中数据列表的列?
- php - 迷你购物车不使用微风缓存插件,随机工作
- python - For 循环仅将单个字符串输入列表,而不是整个单词
- python-3.x - 根据列条件提取熊猫数据框中的特定值
- python - 使用 Chromedriver 的 Python SessionNotCreatedException
- unity3d - 统一的白色不是白色而是米色
- python - 多个 DataLoader Worker 是否可以访问 PyTorch 数据集?