Combo Box No Action
Posted by Rob Camick on May 17, 2009
A common GUI design principle is that the user should be able to use the keyboard or the mouse to achieve the same functionality. Because of this principle I’ve alway been a little puzzled about the default behaviour of a JComboBox. In particular the behaviour is different when using the mouse versus the keyboard when the popup is visible.
Use the mouse to click on the combo box to display the popup. Now try moving the mouse over the items in the popup menu and you will notice that the item becomes highlighted, but it does not become selected. That is, no events are fired and the value in the combo box display area does not change. To select an item and close the popup you must click on the item at which time an ActionEvent is fired.
Now try using the keyboard. Using the down arrow will cause the popup to display. Continue to move through the popup by using the down arrow. This time, not only are the items highlighted, but they also become selected. That is, an ActionEvent is fired and the combo box display area is changed to reflect the selection. The popup is then closed by using the enter key.
In most cases it probably doesn’t matter that the two behaviours are different. However, of the two behaviours I would consider the mouse behaviour to be more natural. Below are the problems I see with the default keyboard behaviour:
- lack of escape functionality – the popup menu can easily be closed using the escape key. However, if you have used the arrow keys to navigate the popup then the original selection has already been lost. The only way to restore it to its original selected item is to find the item again and reselect it.
- unnecessary overhead – you may be using the combo box to select an item in order to display additional information about that item. This information may come from a database. Querying a database for every selection may result in a sluggish GUI.
Now for the good news. If, like me, you don’t like (or want) the ActionEvent to fire when using the arrow keys it can easily be changed. Luckily for us a combo box can also be used as an editor in a JTable. In this case a property is set on the combo box so that the ActionEvent is only fired when the enter key is used. This tells the table to stop editing and save the selected item to the table model. We can use this property on a standalone combo box to achieve the same effect:
Try it out. Even if you don’t make this property the default behaviour its nice to know that it exists just in case you need it sometime.
Note, when using this property in JDK1.4.2 I noticed the the popup menu was not automatically closed when using the enter key. You had to manually close the popup in your ActionListener using code like the following:
The combo box closes automatically in JDK6 and I don’t know when the behaviour was changed.