Search code examples
javamultithreadingclassinstancerunnable

How to access already running instance of a class without creating an actual object


I have a problem with Java GUI. It is hard to explain but I will do my best. I have 2 GUI classes one is class I and other is class G. Class I is initiated from main method. In the class I there is a field (instance of) class G. Reason being that class I collects vital information and passes it to instance of class G. When a button pressed in class I, that sets the class I frame visibility to false and instance of class G to true (showing up the G interface). Problem here is that I want to be able to make a listener in G that sets visibility of I back to true thus displaying the previously edited window. I had a solution of disposing of all frames and creating a new instance but that only shows a new cleared instance of I. Here are some code snippets:

Class I:

Fields:

private JFileChooser j;
private FileFilter filter;
private GUI g;  //<--- it is initialized shortly after.
private Font masterFont;
private JFrame frame;
private JButton done;

private JButton browse1;
private JButton browse2;.....

Sets G visible and I invisible:

class Done implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {

        for (int i = 0; i < 9; i++) {
            System.out.println(array[i]);
        }

        g.setArray(array);
        System.out.println(array);
        setText();
        frame.setVisible(false);
        g.setVisible(true);
        g.setVisible2(false);
        if (g.clear.isSelected()) {
            frame.setVisible(true);
        }


    }

Class G: Note, here I cannot make an instance of I because I keep getting Stack Overflow error.

Hard Reset: This one just creates new instance while disposing the rest (possibly wasteful because the old instance of I is not properly closed)

private class Reset implements ActionListener {
    @Override
        public void actionPerformed(ActionEvent arg0) {
            frame.dispose();
            frame2.dispose();

            Runnable runnable = new Runnable() {
                @Override
            public void run() {
                Intro g = new Intro();
                g.setVisible(true);

            }
        };
        EventQueue.invokeLater(runnable);
    }
}

I want to be able to access the "already running" instance of I without creating any new ones.


Solution

  • You can get the current top level window from the ActionEvent object that is passed into your ActionListener's actionPerformed method. Get the source object that caused the listener to be called via getSource() and then call the SwingUtilities.getWindowAncestor() on the source to obtain the Window (JFrame, JDialog, or whatever it may be).