Add text to JTextArea

223 views Asked by At

I'm trying to append text to a JTextArea. I understand how to add text through an event listener, but I can't seem to fathom how to add the text if, per say, calling a method from a main-method. The text is appended to the JTextArea just fine but the JTextArea component isn't updated/repainted/revalidated/validated (or whatever you're supposed to say :-)).

GUITest

public class GUITest {
    private GUI gui = null;

    public GUITest() {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                gui = GUI.getInstance();

                gui.createAndShowGUI();

                gui.addTxt("Test1");

                gui.addTxt("Test2");

                gui.addTxt("Test3");

                gui.addTxt("Test4");
            }
        });
    }

    public static void main(String[] args) {
        new GUITest();
    }
}

GUI

public class GUI extends JPanel {
    private static final long serialVersionUID = 1L;

    private ConsolePanel console;
    private static GUI instance;

    private GUI() {
        console = new ConsolePanel();

        add(console);
    }

    public static GUI getInstance() {
        if(instance == null) instance = new GUI();

        return instance;
    }

    public void createAndShowGUI() {
        // Create window
        JFrame f = new JFrame("GUI");

        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        f.setBackground(Color.decode("#333333"));
        f.setResizable(false);

        // Create the content pane
        JComponent c = new GUI();

        c.setOpaque(false);
        f.setContentPane(c);

        // Draw the window
        f.pack();
        f.setVisible(true);
    }

    public void addTxt(String txt) {
        console.addTxt(txt);
    }
}

ConsolePanel

public class ConsolePanel extends JPanel {
    private static final long serialVersionUID = 1L;
    private JTextArea console;

    public ConsolePanel() {
        console = new JTextArea("Init...", 10, 10);

        add(console);
    }

    public void addTxt(String txt) {
        console.append(txt);
    }
}

How do I implement the addTxt-method correctly, so that the "Test1", "Test2"... also are added and displayed on the text component?

Fixed:

Changed the line JComponent c = new GUI() to JComponent c = instance.

1

There are 1 answers

7
Hovercraft Full Of Eels On BEST ANSWER

You're creating a new TestGUI (or GUI depending on how you name it) in the createAndShowGUI method, thus you have two of these beasts. Don't do that. Create only one.