Java Swing 实时刷新JTextArea,以显示不断append的内容?
方法一:
在代码中执行完textArea.append("message")后,如果你想让这个更新立刻显示在界面上而不是等swing的主线程返回后刷新,我们一般会在该语句后调用textArea.invalidate()和textArea.repaint()。
问题是这个方法并不能有任何效果,textArea的内容没有任何变化,这或许是swing的一个bug,有一个笨拙的办法可以实现这个效果,就是执行以下语句
textArea.paintImmediately(textArea.getBounds());
或
textArea.paintImmediately(textArea.getX(), textArea.getY(), textArea.getWidth(), textArea.getHeight());
这时,你会发现你刚才append的消息已经被实时地显示出来了。
方法二:
Swing线程之SwingUtilities.invokeLater解释:http://www.importnew.com/15761.html
javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } });
方法三:
不难看出是在等待线程结束导致输出滞后
或许你点击按钮后整个界面都卡住,按钮的事件阻塞了Frame整个线程(不知道这么说是否确切),才导致JTextArea没法实时显示信息
在按钮监听到append事件时,另起一个线程来执行append行为,就好了
private ExecutorService service = Executors.newCachedThreadPool(new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, "output"); } }); public void append() { button1.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { service.submit(new Runnable() { @Override public void run() { 巴拉巴拉啦 巴拉巴拉巴拉 等处理方法 } }); } }); }
参考的链接有:
http://bbs.csdn.net/topics/390230089
http://www.cnblogs.com/Forrest-Janny/p/6610759.html
http://15838341661-139-com.iteye.com/blog/1552332