2014-02-08 83 views
1

當我按下按鈕時,我想在執行方法之前在JTextArea中顯示文本。我使用jTextArea.append()和jTextArea.settext(),但文本出現在方法執行後。我的代碼:如何在jtextarea上附加文本

//...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"); 
     } 
    } 

任何消??

回答

2

actionPerformed()方法由處理所有GUI相關事件的EDT(Event Dispatcher線程)分派。方法內執行的更新將不會更新,直到actionPerformed()方法完成執行。要解決此問題,請在另一個線程中執行myMethodFromOtherClass(),並且只在第二個線程中的方法完成執行後對最終更新事件(jTextArea.append("line after\n");)進行排隊。

的這是一種拙劣的示範如下:

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(); 
    } 
} 

應該更優雅的解決方案來設計請看SwingWorker它是基於一個非常類似的過程,但有更先進的功能。

+0

只要「其他」方法不與GUI交互,在這種情況下,SwingWorker可能是更好的選擇 – MadProgrammer

+0

@MadProgrammer是啊......請注意我的詞「原油」。我想我會在回答中給SwingWorker添加提及。謝謝。 – initramfs

+0

答案沒有錯,問題是缺少的內容是100%確定選擇哪種解決方案;) – MadProgrammer