How can I create and dispose of my forms created with IntelliJ's GUI builder

886 Views Asked by At

I have created a form with IntelliJ's GUI builder, it has a working main() method, the form works properly and has some listeners attached.

In addition to that I have a custom class where I want to call that GUI I created with IntelliJ's GUI builder. I can accomplish this by copying the code within the "main" method in the GUI's class and placing it in my custom class and if I run my custom class the form is indeed displayed.

But thats about all I can do with the created GUI, I can only call it. I can't do other things like dispose that GUI form instance (frame.dispose()) and open another form because I don't know how to get access to the frame instance from my custom class.

Can someone please assist me with this? I thought it would save me a lot of time if I used the GUI builder as opposed to writing the GUI code from scratch for several forms.

2

There are 2 best solutions below

0
ice1000 On

First, give a name to your root panel:

image

Then create a getter for it, and you can use it in a JFrame by

JFrame f = new JFrame();
f.add(new YourGuiClass().getMainPanel());
f.setVisible(true);

When you want to dispose it, dispose the JFrame instance should work.

Edit

You said you want to dispose the JFrame in your GUI form class logic, try this:

class YourGuiClass {
    private JFrame f = new JFrame();
    private JPanel mainPanel;

    public void load() {
       f.add(mainPanel);
       f.setVisible(true);
    }

    public void dispose() {
       f.dispose();
    }
}

By this you can operate the GUI form class without knowing anything related to Swing in the main function:

public static void main(String... args) {
   YourGuiClass myGuiClass = new YourGuiClass();
   myGuiClass.load(); // it now shows itself
   if (someLogic()) myGuiClass.dispose(); // you can
   // also call this elsewhere as you like
}
2
FlashspeedIfe On

I solved the problem by creating a method in the GUI form class called load() which contains the JFrame setup

GUI Form Class

public void load()
{
    JFrame frame = new JFrame( "Login Form" );
    frame.setContentPane( new LoginForm().mainPanel );
    frame.setDefaultCloseOperation( WindowConstants.DISPOSE_ON_CLOSE );
    frame.pack();
    frame.setLocationRelativeTo( null );
    frame.setVisible( true );
}

and then in my main class I called it with new LoginForm().load();.

In order to dispose of the initial GUI form and open another one I created a helper method inside the GUI form class called getMainFrame()

private JFrame getMainFrame()
{
    return (JFrame) SwingUtilities.getWindowAncestor( this.mainPanel );
}

after that inside the GUI form class constructor there is logic to dispose of the frame when a condition is met

if (age.equals("42"))
{
    //load the appropriate form
    new MainForm().load();

    //dispose of this current form
    this.getMainFrame().dispose();
}