2016-05-23 102 views
1

我有已用於填充ComboBox(經理)對象的ArrayList,如下所示:基於爪哇組合框依賴於另一組合框

testingPeople people = new testingPeople(); 
people.loadPeople(); 
ArrayList<Person> testing = new ArrayList<Person>(); 
testing = people.getManagerList(); 
for (int i=0; i < testing.size(); i++) { 
    jComboBox1.addItem(testing.get(i)); 
} 

現在,我要填充第二ComboBox(下屬)取決於第一個ComboBox中選擇的值。在事件處理程序中,我嘗試了以下內容:

if (jComboBox1.getSelectedItem().equals("Insert Name here")) { 
    jComboBox2.addItem("it works!"); 
} 

而且,其他變體,但我仍畫空白。

有人請賜教。

回答

0

jComboBox1的項目監聽器中添加對應於填充jComboBox2的代碼。例如,

ItemListener itemListener = new ItemListener() { 
    @Override 
    public void itemStateChanged(ItemEvent evt) { 
     String item = (String) evt.getItem(); 
     switch (item) { 
      case "Item 1": 
       jComboBox2.removeAllItems(); 
       jComboBox2.addItem("A"); 
       jComboBox2.addItem("B"); 
       jComboBox2.addItem("C"); 
       break; 
      case "Item 2": 
       jComboBox2.removeAllItems(); 
       jComboBox2.addItem("E"); 
       jComboBox2.addItem("F"); 
       jComboBox2.addItem("G"); 
       break; 
     } 
    } 
}; 
jComboBox1.addItemListener(itemListener); 
相關問題