java - 为什么当按下 Jbutton 并在 java 中执行其定义的功能时,我无法在我的应用程序中执行任何操作?
问题描述
这就是我试图做到这一点的方式:
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Hello there");
Thread.sleep(1000);
panel.updateUI();
}
});
我将 Enter 按钮设置为默认按钮,所以当我继续按下它时,按钮可能按下 100 次或更多,但因为我使用Thread.sleep(1000)
它需要一些时间,所以我有时间输入我的 JtextField 甚至关闭窗口但不能做任何事情。
另外,我尝试放入btnNewButton.addActionListener()
线程的运行方法,但没有区别。
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Hello there");
Thread.sleep(1000);
panel.updateUI();
}
});
}
});
thread.start();
// I used try catch block in real code
谁能帮我解决这个问题?
**我正在使用 windowsBuilder 在 Eclipse 中创建此应用程序。
解决方案
不完全确定你的代码应该做什么,但如果你想按下按钮,然后 1000 毫秒后它会检查你的字段,你应该这样做:
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("before 1000ms");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("after 1000ms");
System.out.println("Reading the text field ...");
}
});
thread.start();
System.out.println("after the thread");
输出:
after the thread
before 1000ms
after 1000ms
Reading the text field ...
推荐阅读
- r - 即使在R中重复,如何选择列的最小值?
- python - 如何在 django 管理页面中修复下面的“请更正重复项”?
- java - Java - MySQL 执行存储过程
- flutter - 如何将 ColorFilter 矩阵应用于直接文件或图像并将其保存在颤动中?
- java - 如何将一堆数据添加到链表中
- java - E/AndroidRuntime: FATAL EXCEPTION: main 当我尝试运行并将一个片段连接到另一个片段时
- reactjs - 当我使用 :first-child in Emotion 时如何解决此错误
- ios - Xcode 框架中的混合语言文档生成
- android - 需要关于 onbackpressed 中的 CountDownTimer 的帮助
- mysql - 由 korth 从数据库系统概念创建 time_slot 表