为什么当按下 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()放在线程的run方法中,但没有区别。

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

有人能帮我解决这个问题吗?

**我正在eclipse中使用windowsBuilder创建这个应用程序。

这是因为一种叫做EDT的东西——事件调度线程。

这个专用线程负责GUI中的所有事件,包括绘图(刷新(和交互(按钮单击(。这意味着,用于绘制应用程序的线程与用于执行actionPerformed代码的线程完全相同。由于您实际上是在暂停该线程一段时间,因此您的应用程序在这段时间内将没有响应。

出于不阻塞应用程序的原因,在用户交互上执行的任何内容都应该简短且执行速度快。如果你需要做一些繁重的工作,有一种叫做SwingWorker的工具可以让你在后台线程(池(中轻松地进行一些处理,并在执行过程中安排UI更新(比如进度条的更新(

在你的第二个";线程";代码段,您的线程除了将actionListener添加到按钮之外没有做任何事情,然后它终止(可能在不到1ms之后;(-操作回调仍然由EDT执行。如果您从run方法内部start那个自定义线程,那么它确实是并行的,GUI不会被冻结,但同样,SwingWorker是实现这一点的方法。

不完全确定你的代码应该做什么,但如果你想按下按钮,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 ...

最新更新