0

我有两个 JComboBox;一个删除另一个中的所有项目,如果它已经填充,然后添加一组新项目,第二个触发一个事件,该事件使用所选项目从数据库获取信息。问题发生在第一个组合框删除项目并添加新项目之后;当我选择第二个 JComboBox 中的任何项目时,触发的事件不再发生。

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

第一个组合框

    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(String 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.");
        }
    }
});
4

2 回答 2

0

看起来您的代码永远不会从数据库中获取一组新的项目,因此用户永远不能选择“选择一个单元”以外的任何内容,您的第二个代码块会忽略它。

于 2013-05-02T14:23:19.540 回答
0

它对我有用

try {
     boxListMaterial.removeActionListener(controller);
     boxListMaterial.removeAllItems();
}catch (Exception e){}
boxListMaterial.addActionListener(controller);

控制器 - ActionListener*

于 2021-10-21T12:17:15.903 回答