-1

I have 2 jframes (jframeA,jframeB). On click of button in jframeA and jframeB must close.

jframeA is created at the start up of the project, below is the part of the code that creates the frame and sets it visible.

/*jFrameA*/
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
    @Override
    public void run() {
        new Login().setVisible(true);
    }
    });
}

(The above code is auto-created by netbeans)

I want to close this frame from jframeB. As we can see in the above code there is no object created of jframeA, only the constructor is called and set visibility to true. Since there is no object of jframeA I don't understand how to close this frame from jframeB on click of a button.

Please provide solution.

martinez314
  • 12,162
  • 5
  • 36
  • 63
Sushant Nadkar
  • 183
  • 3
  • 10
  • Please post the jframeB code also – Nima Soroush Nov 21 '14 at 14:11
  • jframeB is also created the same way as jframeA. In the method that is executed on button click will contain the statement to close jframeA. – Sushant Nadkar Nov 21 '14 at 14:22
  • so where are you creating the jframe objects? – Sionnach733 Nov 21 '14 at 14:26
  • the jframe auto generated code only calls the constructor of classes that extends JFrame, as shown in the cose above. – Sushant Nadkar Nov 21 '14 at 14:55
  • 1) See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) 2) Possibly use a [`CardLayout`](http://download.oracle.com/javase/8/docs/api/java/awt/CardLayout.html) as shown in [this answer](http://stackoverflow.com/a/5786005/418556). 3) `new Login()` but then that suggests a modal `JDialog` or a `JOptionPane`.. – Andrew Thompson Nov 21 '14 at 15:17

2 Answers2

1

Since there is no object of jframeA I don't understand how to close this frame from jframeB on click of a button.

If you expect to act on an object, then you need to save a reference to it.

Login jframeA = new Login();
// ...
jframeA.setVisible(false);
jframeA.dispose();
jframeA = null;
martinez314
  • 12,162
  • 5
  • 36
  • 63
0

First import the package of jframeB to jframeA. Write this code at the top of jframeA file.

import JFrameB; //write the name of the package of jframeB instead of "JFrameB"

Assuming the class name of jframeA is FrameA and the class name of jframeB is FrameB, I write below code.

FrameB jframeB = new FrameB();//write this code outside of all the methods but inside of the class.

You said that you use Netbeans. So double click on the button and write the below code inside of the ActionPerformed method.

jframeB.dispose();//this will close jframeB when you click on the button.