当用户点击退出JMenu项时,我正在尝试退出程序。
这是我用来执行动作侦听器的类:
public abstract class ExitListener implements ActionListener {
public void exit(ActionEvent e) {
if (e.getActionCommand().equals("exit")) {
int reply = JOptionPane.showConfirmDialog(null, "Are you sure?", "Quit?", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
}
}
这是初始化按钮的方式:
menuBar = new JMenuBar();
gameMenu = new JMenu("Game");
this.setJMenuBar(menuBar);
menuBar.add(gameMenu);
// Creates the tabs for the Game menu and add's it to the game menu
exit = new JMenuItem("Exit");
gameMenu.add(exit);
当我选择菜单上的退出按钮时,什么也没有发生。
你必须用 JMenuItem#addActionListener
exit.addActionListener(new ExitListener());
内还有一个错误ExitListener
。
应该调用重写的方法actionPerformed
,而不是exit
。这将导致编译错误。
一种更简单的方法是使用匿名类甚至lambda表达式,因为您只想使用ExitListener
一次。
exit.addActionListener(e -> {
if (e.getActionCommand().equals("exit")){
int reply = JOptionPane.showConfirmDialog(null, "Are you sure?", "Quit?", JOptionPane.YES_NO_OPTION);
if (reply == JOptionPane.YES_OPTION){
System.exit(0);
}
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句