求代码
在程序中,添加一个Menu bar,项目为“EXIT”
要求1:这个Exit menu item 与 window’s close box执行相同的任务,且在点击后弹出确认对话框
要求2:为这个“exit”menu item 添加一个快捷键为E
谢谢啦
------解决方案--------------------
不好意思,刚才那段代码关闭时选否也会隐藏窗口,用下面这个
- Java code
import java.awt.*;import java.awt.event.*;import javax.swing.*;public class TestFrame extends JFrame{ private JMenuBar menuBar = new JMenuBar(); private JMenu menu = new JMenu("Menu"); private JMenuItem exitItem = new JMenuItem("EXIT"); public TestFrame() { initMenuBar(); setJMenuBar(menuBar); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent event) { closeWindow(); } }); } private void initMenuBar() { menuBar.add(menu); menu.add(exitItem); exitItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { closeWindow(); } }); exitItem.setMnemonic('E'); } private void closeWindow() { int type = JOptionPane.showConfirmDialog(this, "是否关闭窗口?", "Question", JOptionPane.YES_NO_OPTION); if (type == JOptionPane.OK_OPTION) { System.exit(0); } } public static void main(String[] args) { JFrame frame = new TestFrame(); frame.setSize(400, 300); frame.setLocationRelativeTo(null); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); }}