Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to go back to a JFrames in Java

Tags:

java

swing

jframe

I have a button in a JFrame, if pressed, it takes us to another frame. I used this code:

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {

    SecondForm secondform = new SecondForm();
    secondform.setVisible(true);
    setVisible(false);
    dispose();
    }

So the new frame opens and everything is ok. Then i placed another button -in the second frame- in order to go back to the previous frame. I used this code:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         

    MainForm Mform = new MainForm();
    Mform.setVisible(true);
    setVisible(false);
    dispose();
}                                        

The thing is, i don't think this is the right way to do this. What i want is to:

  • hide the first frame
  • show the new second one
  • dispose the second one
  • show again the first

Is there a way to do that using the first MainForm instance and not creating a new one every time i want to go back. I monitored my program and every time i go back and forth the frames and as i suspected, the ram being used by it keeps increasing.

Thanks in advance.

EDIT : I have a login system and when the user put the correct credentials a new ManiForm instance is created.

MainForm Mform = new MainForm();
Mform.setVisible(true);

That is the instance i want to use. Ii there a way to make MForm visible again from the secondform?

First of all thanks for the help!

I agree that it is easier not to use more than one JFrames, but can you please tell me which is the better way to do what i asked in the first post? The answer Robin gave me is very nice but i don't know what to put as an argument there*:

java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
    *   new SecondForm().setVisible(true);
        }
    });

It's from the auto-generated code from NetBeans.

I tried

new SecondForm(super).setVisible(true);

but i still get compile errors. Apparently i must put super.something() but i don't know what. I tried many but no luck.

like image 871
Christos Baziotis Avatar asked Dec 17 '22 05:12

Christos Baziotis


1 Answers

you shouldn't use more then one frame.

You should have NOTHING in JFrame except defaultExitOperation, size, preferedsize and visible true. Instead place all buttons and fields into a JPanel and add/remove the JPanel from the JFrame.

If you want another Window open use JDialog.

btw: you can have your MainFrame setVisible false and open a JDialog with your MainFrame as parent. Only if someone writes down the right user + password you make the MainFrame visible.

like image 197
MartinL Avatar answered Dec 27 '22 22:12

MartinL