2013-05-02 46 views
0

我有兩個JComboBoxes;如果已經填充了另一個項目,則刪除另一個項目中的所有項目,然後添加一組新的項目,然後使用選定的項目觸發從數據庫獲取信息的事件。問題發生在第一個組合框去除項目並添加新項目之後;當我選擇第二個JComboBox中的任何項目時,發生的事件不再發生。使用removeAllItems()後JComboBox ActionListener不工作

下面我提供了我的代碼片段:

第一個組合框

cmbIDs.addActionListener(new ActionListener() 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      selection = (String)cmbIDs.getSelectedItem(); 
      if (!(selection.equals("Select an username")))//current selection in combobox is stored as string 
      { 
       comboActivate(selection); 
       if (!unitC.getText().equals("")){ 
        unitC.setText(""); 
       } 
       if (!lecturer.getText().equals("")){ 
        lecturer.setText(""); 
       } 

       if (!(courseD.getText().equals("Not Enrolled"))){  
        populateUnits(selection); 
       } 

      } 
      else{ 
       JOptionPane.showMessageDialog(null,"Please select a Surname."); 
      } 
     } 
    }); 

取出裏面populateUnits項目(字符串selectionID):

try 
    { 
     units.removeAllItems(); 
     units.addItem("Select a Unit"); 
    } 
    catch (NullPointerException npe) 
    { 
     units.addItem("Select a Unit"); 
    } 

此指令後發送通過客戶端到服務器查詢數據庫,服務器回覆信息然後添加到第二個JComboBox。我向你保證,在使用removeAllItems()之後,這些項目被添加到JComboBox中。

第二的JComboBox:

units.addActionListener(new ActionListener() 
{ 
    public void actionPerformed(ActionEvent ue) 
    { 
     uSelect = (String)units.getSelectedItem(); 
     if (!(uSelect.equals("Select a Unit")))//current selection in combobox is stored as string 
     { 
      System.out.println(uSelect); 
      unitActivate(uSelect); 
     } 
     else 
     { 
      JOptionPane.showMessageDialog(null,"Please select a Unit."); 
     } 
    } 
}); 
+1

請格式化您的代碼,使其可讀 – LionC 2013-05-02 14:02:57

回答

0

它看起來像你的代碼從來沒有得到一組全新的從數據庫項目,因此用戶不能選擇除「選擇一個單位」等任何東西,這第二個代碼塊忽略。

+0

將方法添加到第二個jcombo框是在選擇第一個JComboBox中的項後完成的。我只是沒有將代碼添加到我現在要嘗試這樣做的問題中。 – user2255225 2013-05-02 14:53:09

+0

添加actionListener在哪裏?你每次刷新單位數據時都調用addActionListener()嗎? – 2013-05-02 15:35:19

+0

不在數據刷新的方法之外調用它。我試着調用刷新數據的方法,但沒有任何區別。 – user2255225 2013-05-02 15:50:34