我有兩個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.");
}
}
});
請格式化您的代碼,使其可讀 – LionC 2013-05-02 14:02:57