简体   繁体   中英

Closing a JFrame after a button is clicked Java

Hello I am writing a sort of Menu for an encryption program I am writing. I finished the core of it, and now i want to try to create a GUI for it. Here is the code for the first Menu:

package matrix_with_GUI;

import javax.swing.*;
import java.awt.event.* ;
import java.awt.* ;

public class Main_Menu extends JFrame implements ActionListener{
     private JButton action1 = new JButton ("");
     private JButton action2 = new JButton ("");
     private JPanel pane = new JPanel();
     private JLabel lbl;

public static void main(String[] args) {
    Main_Menu main = new Main_Menu();
}

public Main_Menu(){
    super();
    JPanel pane=new JPanel();
    setTitle ("Start Menu") ;
    JFrame frame = new JFrame("");

    setVisible(true);
    setSize (380, 260) ;
    setLocation (450, 200) ;
    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE) ;

    action1 = new JButton("Start");
    action2 = new JButton("Exit");
    lbl = new JLabel ("Welcome to the Matrix Encoder/Decoder!!!");
    setLayout(new FlowLayout());

    add (lbl) ;
    add(action1, BorderLayout.CENTER);
    action1.addActionListener (this);
    add(action2, BorderLayout.CENTER);
    action2.addActionListener (this);
}
@Override
public void actionPerformed(ActionEvent event) {
    // TODO Auto-generated method stub
    OptionsMenu x = new OptionsMenu();
    if (event.getSource() == action1)
    {
        System.exit(0);
        x.OptionsMenu();
    }
    else if(event.getSource() == action2){
      System.exit(0);
    }

}

} When the Start Button is clicked, the new menu comes up all fine and good, but the first menu stays open. Is there a way to close this first menu AND open the second menu with the first button click? I'm very new to GUI so the simplest solution would be very helpful. On a side note is there a simple way to move the Start button to the next line? Thanks

You have 2 options: you can use a Window Listener, or you can use the dispose() method. To do the dispose() just type

* This is better to be used with subframes and 2nd level windows.*

this.dispose();

or check this link for using the window listener

Closing JFrame

In order to close the Main_Menu, you can just call its dispose method:

this.dispose();

instead of calling System.exit(0) , which will terminate the JVM altogether.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM