How to avoid firing actionlistener event of JComboBox when an item is get added into it dynamically in java?

后端 未结 9 2282
广开言路
广开言路 2020-12-04 00:23

I need your suggestions and guidence on following task.

I have a frame which has two JComboBoxes supposed they are named combo1 and combo2, a JTable and other compon

9条回答
  •  误落风尘
    2020-12-04 00:40

    The cleaner way is to use lambda expressions like this:

    do(comboBox, () -> comboBox.setSelectedItem("Item Name"));
    

    For the above to work, you need the following method defined somewhere:

    public static void do(final JComboBox component, final Runnable f) {
        final ActionListener[] actionListeners = component.getActionListeners();
        for (final ActionListener listener : actionListeners)
            component.removeActionListener(listener);
        try {
            f.run();
        } finally {
            for (final ActionListener listener : actionListeners)
                component.addActionListener(listener);
        }
    }
    

提交回复
热议问题