关于JOptionPane CANCEL_OPTION

时间:2014-05-16 14:33:51

标签: java swing nullpointerexception joptionpane

我无法将方法的取消选项暗示两次。 (足球的第一个输入对话框和第二个输入对话框)当我单击取消按钮时,出现NullPointerException错误。有什么想法吗?

public void RandomDistribution() {

    String[] gametypes = {"NBA", "Euroleague", "NCAA", "NHL", "Football" };
    String question = "Choose the Game";
    String title = "Memory Game";
    ImageIcon entry = new ImageIcon(getClass().getResource("background.jpg"));
    String c = (String) JOptionPane.showInputDialog(null, question, title,
            JOptionPane.PLAIN_MESSAGE, entry, gametypes,gametypes[4]);

    if (c.equals("Football")) {
        String[] f_level = {"Easy", "Normal", "Hard"};
        String question_f = "Choose the Level";
        String title_f = "Memory Game - Football";
        String c2 = (String) JOptionPane.showInputDialog(null, question_f, title_f,
                JOptionPane.PLAIN_MESSAGE, null, f_level,f_level[2]);
        if (c2.equals("Easy")) {
            c = "Football1";
        } else if (c2.equals("Normal")) {
            c = "Football2";
        } else if (c2.equals("Hard")){
            c = "Football3";
        }
    }

    for (int i = 0; i < 64; i++) {
        PicOfCells[i] = (int) (Math.random() * 64) + 1;
        for (int j = 0; j < i; j++) {
            if (PicOfCells[i] == PicOfCells[j] && i != j && i != 0) {
                --i;
            }
        }
    }

    for (int i = 0; i < 64; i++) {
        PicOfCells[i] = (PicOfCells[i] % 32);
        PicOfAllCells[i] = new ImageIcon(getClass().getResource(PicOfCells[i] + 1 + c +".gif"));
    }
    StartGame.doClick();
}

1 个答案:

答案 0 :(得分:0)

如果我理解正确,那么当您取消其中一个对话框时,问题就是您获得NullPointerException

查看the documentation of JOptionPane.showInputDialog(…)说明当用户取消输入时将返回的内容:

  

...

     

<强>返回:   用户的输入,或null表示用户取消了输入

     

...

所以你的代码

String c = (String) JOptionPane.showInputDialog(null, question, title,
        JOptionPane.PLAIN_MESSAGE, entry, gametypes,gametypes[4]);
当用户取消输入时,

c设置为null。因为你做了

if (c.equals("Football")) {

在下一行中,您尝试在equals(…)引用上调用方法null,这是不可能的,并导致您获得NullPointerException。为了防止抛出异常,您需要检查c null,例如像这样:

if (c == null) {
    // do whatever you want to do when the user canceled input
} else if (c.equals("Football")) {

当然c2 ...; - )

也是如此