2012-10-24 76 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特别是*“我也建议摆脱所有”静态“字段..”* –