Re: Problem handling events on a JCombobox



Luc Van Bogaert wrote:
Hi,

I'm using an editable JComboBox to start a search on a database table. In some cases, the combobox generates two action events (after Enter, and after a selection change) How can I avoid to process the same actionevent code (my search routine) twice?

Thanks!


Luc:

The JComboBox produces ActionEvents on two different actions. One is caused by selecting a new item the other by editing the field. Run my little program below and you will see. If you call setActionCommand("something") on the box that only effects the ActionEvent that is fired when a different item is selected not when you edit and/or press Enter in the editable part of the field. So if you don't want the event that is caused by pressing Enter throw away the event with the action command "comboBoxEdited".

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class test3 {
    public static void main(String[] args) {
        String[] items = {"item1","item2","item3"};
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JComboBox b = new JComboBox(items);
        b.setEditable(true);
        b.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                String ac = ae.getActionCommand();
                System.out.println(ac);
            }
        });
        f.add(b);
        f.pack();
        f.setVisible(true);
    }
}


--

Knute Johnson
email s/nospam/knute/
.



Relevant Pages

  • Re: 2 ActionEvents for 1 selection?
    ... JComboBox that I receive multiple ActionEvents for each single ... A JCheckBox fires one ItemEvent and one ActionEvent whenever ... It looks as if I first get an ActionEvent for the selection of the new ...
    (comp.lang.java.gui)
  • 2 ActionEvents for 1 selection?
    ... Is it correct that if I add an ActionListener to a JCheckBox or a JComboBox that I receive multiple ActionEvents for each single selection I do? ... It looks as if I first get an ActionEvent for the selection of the new item and than an ActionEvent for the unselection of the old item? ...
    (comp.lang.java.gui)