2013-03-15 31 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()); 
}