Closing jFrame after clicking JButton

I developed two JFrames in NetBeans.

When I click the "rules" button (that is, it is located on JFrame1), it opens a second JFrame (but JFrame2 opens in JFrame1, which I don’t want). The second JFrame has a close button. But when I click this button, I want JFrame1 to be open and it works too, but JFrame2 is not actually closed and JFrame1 appears above JFrame2.

In short, the main form is JFrame1. When I click the "rules" button from JFrame1, it opens JFrame2 above JFrame1, and the "close" button appears in JFrame2, when clicked, the main form (for example, JFrame1) is called but launched through JFrame2.

The script is JFframe1 → JFrame2 → JFrame1

Now my question is - after clicking the "rules" button, JFrame1 should be closed and JFrame2 displayed on the screen and vice versa.

+4
source share
6 answers

Assuming your button has an actionListener, after clicking the "rule" button, enter:

JFrame1.dispose(); //Remove JFrame 1 JFrame2.setVisible(true) //Show other frame 

And then rephrase them for the opposite reaction

+7
source

Somethig, like this, should be on the constructor or method that create JFrame2:

 btnCancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { //call another method in the same class which will close this Jframe CloseFrame(); } }); 

This method should close JFrame2

 public void CloseFrame(){ super.dispose(); } 
+3
source

I am not an expert in any way, however, I ran into this problem. If you install a hidden second JFrame, when you click Cancel, it will close the second JFrame.

 //this is the code for the "cancel" button action listener public void actionPerformed(ActionEvent e) { setVisible(false);//hides the second JFrame and returns to the primary 
0
source

this worked for me ( Frame1 Called by RegScreen and Frame2 Called by MainScreen ):

 RegScreen.this.setVisible(false); new MainScreen().setVisible(true); 

Hope this helps :) RegScreen was the original frame open at startup.

0
source

If this does not work, try this.

 JFrame1.dispose(); //Remove JFrame 1 JFrame2.setVisible(true) //Show other frame JFrame2.setVisible(true); this.dispose(); 
0
source
  • Have a MainClass with the main () method.
  • For MainClass, which has a main () method, encapsulate reference variables JFrame1 and JFrame2. Do not use JFrame1 or JFrame2 main () unless you have a specific reason.
  • After something clicked in one of the JFrame objects, create / make another JFrame object visible and utilize it using the methods of the MainProgram.JFrame object.

Example:

  //btn event inside 1st JFrame/window private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { MainProgram.openResultsForm(); //MainProgram opens 2nd window MainProgram.queryEntryForm.dispose(); //MainProgam closes this, //the 1st window } 
0
source

All Articles