如何在showInputDialog中访问JOptionPane命令?

时间:2013-07-27 16:52:12

标签: java swing joptionpane

这是我的代码:

public static void nameset(){
    int no = 1;
    name = JOptionPane.showInputDialog(frame, "The last people who still had cake had to defend it with heir lives, No matter the cost.\nOne of those last people, was you. What is your name?", "",1);     
    if(name.equals("") || name.equals(JOptionPane.CANCEL_OPTION));{
        JOptionPane.showMessageDialog(frame,"Please tell me your name. I don't wanna have to exit out of the game about you.","Hey!",1);
        no++;
    }if (name.equals("") || name.equals(JOptionPane.CANCEL_OPTION)){
        if (no == 2){
            JOptionPane.showMessageDialog(frame, "Seriously? Again?! that's it..");
            if (name.equals(JOptionPane.CANCEL_OPTION)){
                System.exit(0);
            }else{
                System.exit(0);
            }
        }
    }
}

我希望如此,如果您按下取消选项,它会告诉您重新启动。但是如果按取消,它会在控制台中显示错误。我认为这是name.equals(JOptionPane.CANCEL_OPTION),但我不确定。它有什么理由不起作用吗?提前感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

取消按钮将始终返回null。见official JavaDoc

Returns:    user's input, or null meaning the user canceled the input

所以你的病情应该改为:

if(name == null || name.equals(""))

并且您还需要在第一次if声明后删除分号!否则,将始终执行以下块。

一旦修复,你的“3次没有退出”将无法正常工作,因为你实际上没有循环你的输入对话框。

答案 1 :(得分:0)

试试这个

   int no = 1;
   String name = JOptionPane.showInputDialog(null, "The last people who still had cake had to defend it with heir lives, No matter the cost.\nOne of those last people, was you. What is your name?", "",1);     
    if(name == null || name.equals(""));{
        JOptionPane.showMessageDialog(null,"Please tell me your name. I don't wanna have to exit out of the game about you.","Hey!",1);
        no++;
    }if (name == null || name.equals("")){
        if (no == 2){
            JOptionPane.showMessageDialog(null, "Seriously? Again?! that's it.."+name);
            if (name == null || name.equals("")){
                System.exit(0);
            }else{
                System.exit(0);
            }
        }
    }