如何在单击 "exit" MenuItem() 时关闭 window?

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();
    }
}

这里我想在点击退出菜单项时关闭window, 同样在关闭之前,它应该显示一个弹出窗口询问是否关闭如果用户单击确定然后它应该关闭。

这是您的完整解决方案,

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);
         }

    }

    }

}

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.

查看 Closing an Application。它向您展示了如何首先显示 JOptionPane 以确认关闭应用程序。

显示:

  1. 使用 WindowListener 的基本方法
  2. 使用包含的自定义的简化方法 类