【问题标题】:Java JOptionPane Dialog NullPointerExceptionJava JOptionPane 对话框 NullPointerException
【发布时间】:2015-03-21 16:26:40
【问题描述】:

以下代码运行完美,但如果您在对话框中单击“x”或“取消”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)

【问题讨论】:

  • 第 11 行和第 20 行分别是哪几行?如果我不得不猜测我会说 JOptionPane.showInputDialog(null,"This is a test Message",null, JOptionPane.QUESTION_MESSAGE, null,tM1,tM1[0]); 正在返回 null。

标签: java nullpointerexception dialog joptionpane


【解决方案1】:

showInputDialog 返回null,如果您按下“取消”或“X”,那么您的支票if (mA2.equals("Option 1") 将访问null 指针。 之前只需检查mA2 != null

【讨论】:

    猜你喜欢
    • 2021-08-10
    • 2011-12-09
    • 2016-02-02
    • 1970-01-01
    • 1970-01-01
    • 2012-08-27
    • 2012-11-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多