Java JOptionPane 对话框 NullPointerException

Java JOptionPane Dialog NullPointerException

下面的代码运行完美,但是如果你点击对话框中的 "x" 或 "cancel" 就会抛出 NullPointerException。我试图回忆方法 TestMessage 并返回到同一个对话框。

import javax.swing.JOptionPane;

public class Alpha {

  public void TestMessage() {

    Object [] tM1={"Option 1","Option 2","Option 3"};

    String mA2 = (String) JOptionPane.showInputDialog(null,"This is a test Message",null, JOptionPane.QUESTION_MESSAGE, null,tM1,tM1[0]);

    if (mA2.equals("Option 1")) {JOptionPane.showMessageDialog(null,"You chose Option 1");}
    if (mA2.equals("Option 2")) {JOptionPane.showMessageDialog(null,"You chose Option 2");}
    if (mA2.equals("Option 3")) {JOptionPane.showMessageDialog(null,"You chose Option 3");}

    }

    public static void main (String [] args) {

    Alpha A1=new Alpha();
    A1.TestMessage();

    }

    }

错误信息:

java.lang.NullPointerException
at Alpha.TestMessage(Alpha.java:11)
at Alpha.main(Alpha.java:20)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

showInputDialog returns null 如果你按 'Cancel' 或 'X' 那么你的检查 if (mA2.equals("Option 1") 访问一个 null 指针. 之前检查mA2 != null就可以了。