Question

Found a similar topic on here but the solutions provided didn't work (or I'm just not seeing it). Here's my code reduced to the minimum:

Here's the class I want to call the print method from:

{
    HumanInterface gui = new HumanInterface();
    gui.init();
    gui.printToArea("from Main Class");
}

and here's the HumanInterface class which extends JFrame {

JTextArea area = createArea();

public void init() throws InvocationTargetException, InterruptedException
{
    HumanInterface gst = new HumanInterface();
    gst.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    gst.pack();
    gst.setVisible(true);

    printToArea("print from HumanInterface class");
}

public HumanInterface() throws InvocationTargetException,
        InterruptedException
{
    Container container = getContentPane();
    container.setLayout(new GridLayout(2, 3));

    container.add(new JScrollPane(area));
}

public void printToArea(String string)
{
    try
    {
        updateArea(area, string);
    }
    catch (InvocationTargetException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (InterruptedException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

private JTextArea createArea()
{
    final JTextArea area;
    area = new JTextArea();
    area.setBackground(Color.GRAY);

    return area;
}

private void updateTextArea(final JTextArea textArea, final String string)
        throws InvocationTargetException, InterruptedException
{
    SwingUtilities.invokeAndWait(new Runnable()
    {
        @Override
        public void run()
        {
            textArea.append(string);
        }
    });

}

When I call printToArea(...) from anywhere else than from within the HumanInterface class, it doesn't work. What am I missing?

Was it helpful?

Solution

The GUI you see is not the GUI you "want" to see, it's a second ;-)

In your init() function you create a second HumanInterface:

HumanInterface gst = new HumanInterface();
gst.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gst.pack();
gst.setVisible(true);

I think you probably want that (not tested):

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top