2013-03-15 75 views
1

我想要使用for循环从我的类文件中获取名称到String数组,并将其显示在JOptionPane列表菜单中。但是,我面临NullPointerException,但如果我没有将String数组声明为null,编译器会抱怨。JOptionPane中的选项值

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"); 
} 

无需我一个一个地列出选项值,我该如何解决这个问题?

+0

如何以及在哪里填充'theNames'字符串数组? – Smit 2013-03-15 18:48:11

回答

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

我注意到你班上有一个人员变量。 你能向我解释为什么你把名字初始化为null吗?它的方法有什么好处?

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()); 
}