2012-10-24 75 views
3

因此,我正在製作的程序使用2個線程:一個用於GUI,一個用於執行工作。添加文本到JTextArea(追加或設置文本)

我想從工作線程/類更新以在GUI類中的JTextArea上打印出來。 我試過的所有東西似乎都不起作用。我添加了行來在控制檯上打印出文本,然後將文本添加到JTextArea中,以確保它已到達行,但每次控制檯都獲得文本但GUI中的JTextArea沒有發生更改。

public static void consoleText(String consoleUpdate){ 
    GUI.console.append(consoleUpdate); 
} 

我在工作班上試過這個,但沒有發生任何事。 任何人都知道如何解決我的問題?

編輯:

MAIN.JAVA

public class main { 
public static void main(String[] args) { 
    Thread t1 = new Thread(new GUI()); 
    t1.start(); 
} 

GUI.JAVA

public class GUI extends JFrame implements Runnable{ 

public static JTextArea console; 
private final static String newline = "\n"; 

public void run(){ 
    GUI go = new GUI(); 
    go.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    go.setSize(350, 340); 
    go.setVisible(true); 
} 

public GUI(){ 
setLayout(new FlowLayout()); 
console = new JTextArea(ConsoleContents, 15, 30); 
add(console); 
} 

WORK.JAVA

...{ 
consoleText("\nI want this text on the JText Area"); 
} 

public static void consoleText(String consoleUpdate){ 
    GUI.console.append(consoleUpdate); 
} 
+1

不知道如何任何人都可以幫助你,更快地發佈[SSCCE](http://sscce.org/),簡短,可運行,可編譯,僅關於'JTextArea#append(「String」 )' – mKorbel

+0

歡迎在這個論壇上,請[請參閱常見問題](http://stackoverflow.com/faq) – mKorbel

+1

好吧我會嘗試截斷它足以發佈 – Emm

回答

1

首先,正如人們所說的,你的GUI應該只有在事件派發線程上運行。

就像它寫的,你的GUI類有兩件事:它是一個框架,一個可運行的,並且兩個 被完全獨立使用。事實上,在GUI對象上調用「運行」會創建另一個不相關的GUI對象。這可能就是你什麼都看不到的原因。

所以我建議讓您的主要如下:

... main(...) { 
    SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      GUI gui= new GUI(); 
      gui.setVisible(true); // and other stuff 
     } 
    }); 
} 

(我也建議擺脫所有的「靜態」 BTW領域這可能是你的問題的根源 ,用奇怪的地方沿。 「運行」方法)。

現在,你的 「consoleText」 的方法,我假設你從另一個線程調用,不應該直接 修改文本,但撥打SwingUtilities.invokeLater()這樣做:

public void consoleText(final String consoleUpdate){ 
SwingUtilities.invokeLater(new Runnable() { 
    public void run() { 
     console.append(consoleUpdate); 
    } 
}); 

}

(「final」聲明很重要,因爲它允許Runnable使用consoleUpdate變量)。

+0

很好的答案。 +1特別是*「我也建議擺脫所有」靜態「字段..」* –