Skip to content
Advertisement

event when press exit button: JOptionPane.showInputDialog

How can I add a function after clicking on the cancel or exit button? I tried it like this but it doesn’t work for me.

It shows me an error that choice is null but it couldn’t be because it is int? is there any other possibility to solve it?

public void start() {
        
        int choice = Integer.parseInt(JOptionPane.showInputDialog(null, "Choice: n 1 - Play a game n 2 - show all games n 3 - Find the best score n 4 - Find a player n 5 - End"));
        //if (choice == JOptionPane.OK_OPTION) {
            switch (choice) {
                case 1:
                    this.play();
                    break;
                case 2:
                    this.allGames();
                    break;
                case 3:
                    this.getBestScore();
                    break;
                case 4:
                    this.getPlayer();
                    break;
                case 5:
                    System.exit(0);
                    break;
                default:
                    JOptionPane.showMessageDialog(null, "Wrong input.");
                    break;
            }
        // } else if (choice == JOptionPane.CANCEL_OPTION) {
            // System.exit(0);
        // } else if (choice == JOptionPane.CLOSED_OPTION) {
            // System.exit(0);
        // }
        
        
        
    }

Advertisement

Answer

When you press the “exit” or “cancel” button, you are assigning “choice” to null, but that won’t work because choice is an int. You could make “choice” a String and then, before the switch statement, make sure choice!=null. This is what that would look like

public static void start() {
        String choice = JOptionPane.showInputDialog(null, "Choice: n 1 - Play a game n 2 - show all games n 3 - Find the best score n 4 - Find a player n 5 - End");
       if(choice!=null) {
        switch (choice) {
                case "1":
                    play();
                    break;
                case "2":
                    allGames();
                    break;
                case "3":
                    getBestScore();
                    break;
                case "4":
                    getPlayer();
                    break;
                case "5":
                    System.exit(0);
                    break;
                default:
                    JOptionPane.showMessageDialog(null, "Wrong input.");
                    break;
                    }
        }
} 
Advertisement