Combo Box Prompt
Posted by Rob Camick on October 18, 2008
You have a JComboBox on a crowded form and there is no room to display a label describing the usage of the combo box. Or, maybe you just don’t want to use a label. In either case, you need to display a prompt message in the combo box indicating its usage. One way to do this is to simply use the first item of the combo box as the prompt message and then make this item the selected item. But what if you don’t want the prompt message to be part of the combo box drop down?
The second approach would be to display the prompt message only when no item has been selected in the combo box. The combo box uses the same renderer to render the items in the drop down list and to render the selected item in the combo box display area. When no item has been selected, the value to be rendered in the display area is null. The PromptComboBoxRenderer takes advantage of this and allows you to render the specified message instead of the null value.
The main difference between the two approaches is that in the second approach, once an item has been selected you will never see the prompt message again. So depending on your requirement this may, or may not, be a solution for you.
It only takes a single line of code to enable a combo box to use the prompt renderer:
comboBox.setRenderer(new PromptComboBoxRenderer("Select Color"));
Also, when the combo box is created the first item in the combo box is selected so you will need to clear the selection by using:
The combo box in its normal state…
and with the drop down open…