macdays
macdays

Reputation: 63

How do I remove all items from a jComboBox without triggering an action listener?

When I try to clear the items listed in my JComboBox it triggers my ActionListener that is tied to the combo box. I have another function that gets called recursively as a result and is generating a duplicate value. Is there a way to temporarily disable the action listener and remove everything from the JComboBox without triggering an event?

jComboBox_database.removeAllItems();

jComboBox_database.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jComboBox_database.addActionListener(new java.awt.event.ActionListener() {
    @Override
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        jComboBox_databaseActionPerformed(evt);

Upvotes: 2

Views: 760

Answers (2)

Abra
Abra

Reputation: 20914

As far as I am aware, you cannot "disable" an ActionListener.

The ActionListener will be notified whenever the JComboBox selection changes. Clearing the items also sets the "selected item" to null, thus invoking your actionPerformed method.

Assuming you only want to call your recursive method when you actually select a value, maybe you should implement ItemListener instead.

jComboBox_database.addItemListener(new java.awt.event.ItemListener() {
    public void itemStateChanged(java.awt.event.ItemEvent evt) {
        if (evt.getStateChange() == ItemEvent.SELECTED) {
            jComboBox_databaseActionPerformed(evt);
        }
    }
});

Of-course, you may need to also change the parameter to your method jComboBox_databaseActionPerformed since an ItemEvent is not exactly the same as an ActionEvent.

Another alternative would be to simply call method removeActionListener before you clear the JComboBox and then call method addActionListener after.

Upvotes: 3

Sorin
Sorin

Reputation: 1007

You could change the ActionCommand of your JComboBox before and after you removeAllItems().

String oldCommand = jComboBox_database.getActionCommand();
jComboBox_database.setActionCommand("cmdIgnore");
jComboBox_database.removeAllItems();
jComboBox_database.setActionCommand(oldCommand);

and in your ActionListener:

public void actionPerformed(java.awt.event.ActionEvent evt) {
    if( ! "cmdIgnore".equals(evt.getActionCommand())) {
        jComboBox_databaseActionPerformed(evt);
    }
}

Upvotes: 0

Related Questions