【问题标题】:event when press exit button: JOptionPane.showInputDialog按下退出按钮时的事件:JOptionPane.showInputDialog
【发布时间】:2022-01-26 01:10:35
【问题描述】:

点击取消或退出按钮后如何添加功能?我试过这样,但它对我不起作用。

它向我显示了一个错误,即选择为空,但它不可能是因为它是 int?有没有其他办法解决?

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

【问题讨论】:

    标签: java swing


    【解决方案1】:

    当您按下“退出”或“取消”按钮时,您将“选择”分配给 null,但这不起作用,因为选择是一个 int。您可以“选择”一个字符串,然后在 switch 语句之前,确保选择!= null。这就是它的样子

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

    【讨论】:

    • 非常感谢,我想用一个 int 但它太傻了,它可以工作
    猜你喜欢
    • 2013-10-11
    • 1970-01-01
    • 2011-01-22
    • 2015-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-02
    • 2016-03-30
    相关资源
    最近更新 更多