方法一:
在代碼中執行完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