javajmenumessagedialog

JMenu repeadly show showMessageDialog


I set 2 Jmenu items, one is "New game", another is "About the game". However, when I run the program and press "New game" , the dialog of "About the game" was shown, so how can I solve this problem?

 public Game() {
     JMenuBar menuBar = new JMenuBar();
     this.mainFrame.setJMenuBar(menuBar);
     JMenu aMenu = new JMenu ("New Game");
     menuBar.add(aMenu);
     newMenuItem("New Game", aMenu, this);
     JMenu bMenu = new JMenu("About");
     menuBar.add(bMenu);
     newMenuItem("About the game",bMenu,this);

      }


 public void aboutGame () {
    final String AboutGameText = 
               " The game is about...";
         JOptionPane.showMessageDialog(this.mainFrame, AboutGameText, "About the game", JOptionPane.PLAIN_MESSAGE);

   }



  public void actionPerformed(ActionEvent arg0) {
    if (arg0.getActionCommand().equals("New Game")) Game();
    if (arg0.getActionCommand().equals("About the game")); aboutGame();


}

Solution

  • In the line

    if (arg0.getActionCommand().equals("About the game")); aboutGame();
    

    You have a semicolon after the if statement. Essentially that reduces the if statement to just the if with no body. So the jvm will process whether it is true or false, throw away the results, and move onto the next line, which is the aboutGame() line. If you remove it the problem should go away. By the way its never a good idea to omit the braces, even on one line if statements

    if (arg0.getActionCommand().equals("About the game")) {
        aboutGame();
    }