Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make window close on clicking "exit" MenuItem()?

public class Manubar extends JFrame {

    JMenuBar jmb;
    JMenu jm;
    JMenu jm2;
    JMenuItem jmt;
    JMenuItem jmt2;

    public Manubar() {
        setSize(500, 500);

        jmb = new JMenuBar();
        jm = new JMenu("file");
        jm2 = new JMenu("edit");
        jmt = new JMenuItem("copy");
        jmt2 = new JMenuItem("exit");
        jmb.add(jm);
        jmb.add(jm2);
        jm.add(jmt);
        jm.add(jmt2);
        add(jmb, BorderLayout.NORTH);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

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

Here I want to close the window when I click on exit menu item, also before closing, it should display a popup to ask whether to close if user clicks OK then it should close.

like image 813
chris Avatar asked Dec 06 '25 02:12

chris


2 Answers

Here I want to close the window when I click on exit menu item, also before closing, it should display a popup to ask whether to close if user clicks OK then it should close.

Check out Closing an Application. It shows you how to display a JOptionPane to confirm closing of the application first.

It shows:

  1. the basic approach of using a WindowListener
  2. a simplified approach by using the included custom classes
like image 91
camickr Avatar answered Dec 08 '25 16:12

camickr


Here is your complete solution,

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class Manubar extends JFrame implements ActionListener {

    JMenuBar jmb;
    JMenu jm;
    JMenu jm2;
    JMenuItem jmt;
    JMenuItem jmt2;

    public Manubar() {
        setSize(500, 500);

        jmb = new JMenuBar();
        jm = new JMenu("file");
        jm2 = new JMenu("edit");
        jmt = new JMenuItem("copy");
        jmt2 = new JMenuItem("exit");
        jmb.add(jm);
        jmb.add(jm2);
        jm.add(jmt);
        jm.add(jmt2);
        add(jmb, BorderLayout.NORTH);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jmt2.addActionListener(this);
    }

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

    @Override
    public void actionPerformed(ActionEvent e) {

       if("exit".equals(e.getActionCommand())){

         int dialogButton = JOptionPane.YES_NO_OPTION;
         JOptionPane.showConfirmDialog (null, "Would You Like to Save your Previous Note First?","Warning",dialogButton);

         if(dialogButton == JOptionPane.YES_OPTION){
            System.exit(NORMAL);
         }

    }

    }

}
like image 41
Vishal Gajera Avatar answered Dec 08 '25 16:12

Vishal Gajera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!