1

我正在尝试使用 for 循环将名称从我的类文件中获取到一个String数组中,并将其显示在JOptionPane列表菜单中。但是,我面临一个NullPointerException但是如果我不将String数组声明为null,编译器会抱怨。

public void showWindow()
{
    String[] theNames = null;

    for(int i=0; i<person.length; i++)
    {
        if(person[i] != null)
        {
            System.out.println(person[i].name);
        }
    }

    String s = (String)JOptionPane.showInputDialog(null, "Select your name and click on confirm", "Results", JOptionPane.PLAIN_MESSAGE, null, theNames, "Eric");
}

如果不一一列出选项值,我该如何解决这个问题?

4

2 回答 2

0

选项可以是任何对象的数组,但请确保 toString() 方法是您希望在下拉菜单中显示的内容。无需一一列出选项,甚至无需将对象转换为字符串。例如:

public class Person {

  String firstName, lastName;

  public Faculty(String f, String last) {
     firstName = f;
     lastName = last;
  } 

  public String toString() {
     return firstName + " " + lastName;
  }  
}

public static void showWindow()  {
  Person[] guys= new Person[5];
  guys[0] = new Person("Dick","Wall");
  guys[1] = new Person("Tor","Norbye");
  guys[2] = new Person("Chet","Haase");
  guys[3] = new Person("Carl","Quinn");
  guys[4] = new Person("Scott","Hanselman");

  Personp = (Person) JOptionPane.showInputDialog(null, 
     "Pick your favorite podcaster.", 
     "Java Posse",
     JOptionPane.QUESTION_MESSAGE, null, 
     guys, guys[0]); 

  System.out.println("You picked:" + p.toString());
}
于 2013-03-15T19:32:56.327 回答
0

那行代码没有问题:

String [] theNames = null;  
      String s=(String)javax.swing.JOptionPane.showInputDialog(null, "Select your name and click on confirm","Results",
              javax.swing.JOptionPane.PLAIN_MESSAGE, null, theNames, "Eric");
      System.out.println(s);

注意:您必须初始化theNames,除非您将获得RuntimeException.

我注意到您的班级中有一个 Person 变量。你能向我解释为什么你将 theNames 初始化为 null 吗?它在方法中有什么好处?

于 2013-03-15T19:02:22.323 回答