简体   繁体   中英

Trouble Adding text to JTextArea (append or settext)

So the program I am making uses 2 threads: One for the GUI and one to do the work.

I want updates from the work thread/class to print out on JTextArea in GUI class. Everything I tried didn't seem to work. I added lines to print out text on the console right after lines to add text to the JTextArea to make sure it had got to the line but everytime console got text but no changes happened to JTextArea in the GUI.

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

I tried this in the work class but nothing happened. Anyone know how to fix my problem?

Edit:

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

First, as has been said, your GUI should only run on the Event dispatch thread.

As it is written, your GUI class does two things : it's a frame, and a runnable, and both are used completely independently. As a matter of fact, calling "run" on a your GUI object creates another, unrelated GUI object. That's probably the reason why you see nothing.

So I suggest making your main the following:

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

(I would also suggest getting rid of all "static" fields BTW. It's probably the source of your problems, along with the weird place of the "run" method).

Now, your "consoleText" method, which I assume you call from another thread, should not modify the text directly, but call SwingUtilities.invokeLater() to do so :

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

}

(the "final" declaration is important, as it allows the Runnable to use the consoleUpdate variable).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM