Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closing jFrame after clicking JButton

I have designed two JFrames in NetBeans.

When I click the "rules" button (i.e placed on JFrame1) then it opens a second JFrame (but JFrame2 opens over JFrame1's window, that's what I dont want). In the second JFrame there is a "close" button. But when I click this button, I want JFrame1 to be opened and it is working too, but JFrame2 is actually not closed and JFrame1 is appearing over JFrame2.

In short the main form is JFrame1. When I click the "rules" button from JFrame1 it opens JFrame2 over JFrame1, and in JFrame2 there is a "close" button when it gets clicked the main form (i.e JFrame1) is lauched but it is launched over JFrame2.

The scenerio 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.

like image 678
Ankush Pruthi Avatar asked Sep 21 '13 09:09

Ankush Pruthi


People also ask

How do you make a JFrame close when a button is pressed?

You can use super. dispose() method which is more similar to close operation. Show activity on this post. You cat use setVisible () method of JFrame (and set visibility to false ) or dispose () method which is more similar to close operation.

How do I exit a JButton?

The quickest, easiest and most robust way to simply close a JFrame or JPanel with the click of a JButton is to add an actionListener to the JButton which will execute the line of code below when the JButton is clicked: this. dispose();

How do you exit a JFrame?

You can easily close your JFrame by clicking on the X(cross) in the upper right corner of the JFrame. However JFrame. setDefaultCloseOperation(int) is a method provided by JFrame class, you can set the operation that will happen when the user clicks the X(cross).


2 Answers

Assuming your button has an actionListener, after clicking the "rules button" put in:

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

And then reverese them for the opposite reaction

like image 77
Levenal Avatar answered Oct 12 '22 23:10

Levenal


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

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

It's method which should close JFrame2

public void CloseFrame(){
    super.dispose();
}
like image 43
Aleksey Dz Avatar answered Oct 12 '22 22:10

Aleksey Dz