2016-06-26 10 views
-1

終了JMenuアイテムにヒットしたときにプログラムを終了しようとしています。Jmenuボタンが押されたときにJava用のアクションリスナーを使用してプログラムを終了させる

これは私がアクションリスナーを実行するために使用しているクラスです。

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

私はメニューの終了ボタンを選択すると、何も起こりません。

+1

あなたはどこにいたのかを忘れてしまった:)。 –

答えて

1

あなたはエラーがExitListener以内もありJMenuItem#addActionListener

exit.addActionListener(new ExitListener());

を使用する必要があります。

オーバーライドされたメソッドは、ではなく、exitと呼びます。これにより、コンパイルエラーが発生します。


簡単な方法は、あなたが唯一の私が推測たら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); 
       } 
     } 
}); 
関連する問題