【问题标题】:JComboBox ActionListener not working after removeAllItems() was used使用 removeAllItems() 后 JComboBox ActionListener 不起作用
【发布时间】:2013-04-26 17:38:48
【问题描述】:

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

下面我提供了我的代码的sn-ps:

第一个组合框

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

【问题讨论】:

  • 请格式化您的代码以使其可读

标签: java actionlistener jcombobox removeall


【解决方案1】:

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

【讨论】:

  • 第一个JComboBox中的一个项目被选中后,添加项目到第二个JComboBox的方法完成。我只是没有将代码添加到我现在将尝试这样做的问题中。
  • actionListener 添加在哪里?每次刷新数据的时候都是在调用 addActionListener() 吗?
  • 不,它在刷新数据的方法之外调用。我尝试调用刷新数据的方法,但没有任何区别。
  • update- 在我将 actionlistener 保留在方法之外之前,当我也在刷新数据方法中调用它时。我只是在方法中尝试了它,现在 actionlistener 终于在做某事了。它似乎没有完全工作。一会儿又更新了
  • 好的,所以动作监听器只在第一次刷新时起作用,之后不起作用。我想也许我还应该在使用 removeallitems 时删除动作侦听器,然后在刷新数据后再次添加它。
【解决方案2】:

对我有用

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

控制器 - ActionListener*

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多