简体   繁体   中英

close JFrame on button click

I am making a menu system. I have run into a problem.. Whenever I press the button to move to the next menu, the old JFrame stays open behind the new one. Code is:

public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                MainMenu frame = new MainMenu();
                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

/**
 * Create the frame.
 */
public MainMenu() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setBounds(100, 100, 450, 300);
    contentPane = new JPanel();
    contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
    setContentPane(contentPane);
    contentPane.setLayout(null);

    JButton btnStart = new JButton("Start Game");
    btnStart.setBounds(154, 82, 126, 23);
    contentPane.add(btnStart);

    JLabel lblBattleKoalas = new JLabel("Battle Koalas");
    lblBattleKoalas.setFont(new Font("Times New Roman", Font.BOLD, 35));
    lblBattleKoalas.setBounds(121, 11, 219, 48);
    contentPane.add(lblBattleKoalas);

    JButton btnNewButton = new JButton("Player Menu");
    btnNewButton.setBounds(154, 116, 126, 23);
    contentPane.add(btnNewButton);
    btnStart.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Game.main(null);

        }
    });
    btnNewButton.addActionListener(new DispPlayer());
}

static class DispPlayer implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        PlayerMenu.main(null);
        //Close Current Frame Here
    }

}

} How would I get the MainMenu to close and the PlayerMenu to open up? Any help would be great!

The method setVisile(boolean b) isn't used only to make frames appear, you can also use it to make them disapear. For example, if frame is your MainMenu object, you might want to call frame.setVisible(false); when someone presses the button you want them to.

So.. Lets consider your button is btn , that your first menu was oldMenu and the menu you'd like to display is newMenu . I believe you could write:

    btn.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        oldMenu.setVisible(false);
        //don't forget to create the new menu
        newMenu.setVisible(true);
      }
    }

I figured out my problem. I needed to do MainMenu.this.dispose(); to access the JFrame

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