Search code examples
javaswingjbutton

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.


Solution

  • 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