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.
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.
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();
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).
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
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With