我有申请:
- 一个用于用户输入的 JTextField,
- 一个 JLabel 来显示忙碌状态,
- 一个 JTextArea 用于打印搜索结果。
我希望用户将文本写入文本字段,按回车键并查看结果。我有这样的听众:
private void searchForPattern(java.awt.event.ActionEvent evt) {
textArea.setText("");
busyLabel.setText("Searchnig ...");
doSearch();
busyLabel.setText("Idle");
}
在doSearch中有一个相当复杂的算法,打开大量的XML文件并搜索给定的模式,这需要一段时间。 busyLabel 的文本更改为 Searching ... 只有在 doSearch 完成后。 doSearch没有第二个线程,只有很多IO操作。
我该如何解决这个问题?
最佳答案
您遇到了一个经典的 Swing 并发问题(教程:Concurrency in Swing),其中 doSearch 占用了 Swing 事件线程。由于此线程是 Swing 进行所有绘制/绘制和与用户交互的地方,如果它被需要任何可察觉的时间来完成的代码捆绑,整个应用程序将“卡住”,没有组件得到更新和所有用户交互被忽视。
解决方案:在后台线程上执行此操作,例如 SwingWorker 对象提供的线程。在 SwingWorker 的 done()
方法中将“空闲”字符串设置到 JLabel。
即,
private void searchForPattern(java.awt.event.ActionEvent evt) {
textArea.setText("");
busyLabel.setText("Searching ...");
new SwingWorker<Void, Void>() {
@Override
protected Void doInBackground() throws Exception {
doSearch();
return null;
}
@Override
protected void done() {
busyLabel.setText("Idle");
}
}.execute();
}
关于java - Swing:调用 jLabel.setText 太晚了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10372046/