[英]How to append text on a jtextarea
When I push a button, I want to show text in a JTextArea before executing a method. 当我按下按钮时,我想在执行方法之前在JTextArea中显示文本。 I use jTextArea.append() and jTextArea.settext() but the text appears after method execution.
我使用jTextArea.append()和jTextArea.settext(),但文本在方法执行后出现。 My code:
我的代码:
//...JTextArea jTextArea;
JButton btnGo = new JButton("Start");
btnGo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jTextArea.append("line before\n");
myMethodFromOtherClass();
jTextArea.append("line after\n");
}
}
Any sugestion? 有什么建议吗?
The actionPerformed() method is dispatched by the EDT (Event dispatcher thread) which handles all GUI-related events. actionPerformed()方法由处理所有与GUI相关的事件的EDT(事件分派器线程)分派。 Updates performed within the method will not be updated until the
actionPerformed()
method completes execution. 在
actionPerformed()
方法完成执行之前,不会更新在方法中执行的更新。 To solve this, perform myMethodFromOtherClass()
in another thread, and only queue the final update event ( jTextArea.append("line after\\n");
) after the method completes execution in the second thread. 若要解决此问题,请在另一个线程中执行
myMethodFromOtherClass()
,并在方法在第二个线程中完成执行之后,仅将最终更新事件( jTextArea.append("line after\\n");
) jTextArea.append("line after\\n");
。
A crude demonstration of this is shown below: 对此的粗略演示如下所示:
JButton btnGo = new JButton("Start");
btnGo.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
//Leave this here
jTextArea.append("line before\n");
//Create new thread to start method in
Thread t = new Thread(new Runnable(){
public void run(){
myMethodFromOtherClass();
//Queue the final append in the EDT's event queue
SwingUtilities.invokeLater(new Runnable(){
public void run(){
jTextArea.append("line after\n");
}
});
}
});
//Start the thread
t.start();
}
}
Should a more elegant solution be devised please look at SwingWorker which is based on a very similar procedure but with more advanced features. 如果要设计一个更优雅的解决方案,请查看SwingWorker ,它基于非常相似的过程,但具有更多高级功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.