Java 为什么jTextArea.setText()方法在它应该工作之后工作?
对不起,伙计们,这可能是个愚蠢的问题,但我真的找不到类似的情况 这是我的密码:Java 为什么jTextArea.setText()方法在它应该工作之后工作?,java,swing,while-loop,jtextarea,Java,Swing,While Loop,Jtextarea,对不起,伙计们,这可能是个愚蠢的问题,但我真的找不到类似的情况 这是我的密码: private void startHashingButtonActionPerformed(java.awt.event.ActionEvent evt) { consoleArea.setText( myFile.getName() + " started to be hashing! It can
private void startHashingButtonActionPerformed(java.awt.event.ActionEvent evt) {
consoleArea.setText( myFile.getName() + " started to be hashing! It can take few minutes, please wait.."); //20:05
try {
BufferedReader reader = new BufferedReader(new FileReader(myFile));
myHash = new HashOA(300000);
try {
while(reader.readLine() != null){
myHash.hash(reader.readLine());
}
consoleArea.append("\n" + myFile.getName() + " is successfully hashed!!");
} catch (IOException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
我希望在consoleArea(TextArea)中应该有“file.txt开始进行散列!可能需要几分钟,请稍候…”写入,然后应该启动散列过程(while(reader.readLine()!=null)循环)。但当我运行程序并单击“startHashingButton”时,它首先完成了散列过程,然后在控制台(jTextArea)上写入-->“file.txt开始散列!可能需要几分钟,请稍候…”,“file.txt已成功散列!!”
我正在处理一个大的文本文件,需要一段时间来散列它。这就是为什么我想告诉用户他/她应该等一会儿
为什么工作队列与我的代码顺序不同
注意:我唯一想到的是使用线程,它能解决问题吗
注意:我唯一想到的是使用线程,它能解决问题吗
是的,没错。在事件侦听器中执行的代码在事件分派线程上被调用。在所有代码执行完毕之前,无法重新绘制GUI。因此,长时间运行的任务会阻止GUI重新绘制自身
有关更多信息,请阅读上的Swing教程部分。与创建自己的线程相比,
SwingWorker
可能是更好的解决方案。使用SwingWorker实现工作线程。
在doInBackground方法中执行所有处理,您可以在doInBackground中添加以下代码。在此之前,您将在控制台区域中设置文本。一旦对文件进行哈希处理,就可以实现done()方法并在控制台区域中设置适当的消息。给你一个想法,它看起来像这样
@Override
protected Integer doInBackground() throws Exception {
try {
BufferedReader reader = new BufferedReader(new FileReader(myFile));
myHash = new HashOA(300000);
try {
while(reader.readLine() != null){
myHash.hash(reader.readLine());
}
return null;
} catch (IOException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(MainScreen.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
protected void done() {
consoleArea.append("\n" + myFile.getName() + " is successfully hashed!!");
}
请参阅此链接以获得更清晰的信息:@user2949556或consoleArea.append(…应包装到invokeLater()@camickr中感谢您的课程链接,我从中学到了很多。正如您所说,SwingWorker是解决方案。这提供了很多想法,谢谢,但在那个done(Void result)方法中(Void result)为什么会这样(Void result)代表?在我的代码中,该部分不起作用,但有一个空部分“done()”一切正常。我编辑了我的答案,删除了无效的结果。(输入错误)仅供参考,如果要获取doInBackground()中返回的结果,可以在done()中调用get()方法它将返回您所返回的对象。@user2949556,
但是在那个done(Void result)方法中,为什么那个(Void result)代表什么?在我的代码中,那个部分不起作用,但有一个空的“done()”一切都进行得很顺利
这就是我给你提供教程链接的原因。该链接包含一个工作示例和一个解释。阅读教程和自己编写代码比复制代码能学到更多。