JOptionPane关闭框架上没有按钮

时间:2016-07-17 12:44:00

标签: java netbeans switch-statement joptionpane system.exit

我在JOptionPane上有这段代码片段。我想在单击是按钮时打开另一个框架,并在单击否或取消时关闭框架。

在我将案例1和案例2设置为System.exit(0)之前;案例0工作得非常好,因为它成功地打开了另一个框架。但是当我单击Yes按钮时将system.exit置于case 1和2时它仍会关闭框架。

int test = JOptionPane.showConfirmDialog(null, "You lost! Play again?");

         switch(test) {
             case 0:  RPS rps = new RPS();
                        rps.setVisible(true);
                        this.dispose(); //Yes option
             case 1: System.exit(0); //No option
             case 2: System.exit(0); //Cancel option
           }

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您忘记在代码中添加break语句。

编辑后,您的代码可能如下所示:

int test = JOptionPane.showConfirmDialog(null, "You lost! Play again?");
switch(test) {
case 0: RPS rps = new RPS();
        rps.setVisible(true);
        this.dispose(); // Yes option
        break;
case 1: System.exit(0); // No option
case 2: System.exit(0); // Cancel option
}

最好使用JOptionPane提供的常量,如下所示:

int test = JOptionPane.showConfirmDialog(null, "You lost! Play again?");
switch(test) {
case YES_OPTION: RPS rps = new RPS();
                 rps.setVisible(true);
                 this.dispose(); // Yes option
                 break;
case NO_OPTION: System.exit(0); // No option
case CANCEL_OPTION: System.exit(0); // Cancel option
}