Java Tips Weblog

  • Blog Stats

    • 2,076,564 hits
  • Categories

  • Archives

  • Advertisements

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…

Get The Code

Related Reading

Providing a Custom Renderer


5 Responses to “Combo Box Prompt”

  1. Anonymous said

    Hi, can you please tell me what am I doing wrong? I can’t get it work. I’ve set the renderer and then the selected index, but the prompt just doesn’t appear, what can be wrong, thank you very much

    • Anonymous said

      Never mind, I got it. Thank you very much this was the most usefull for me. Thanks again, great job.

  2. Anonymous said

    Doesn’t work for me.

  3. Anonymous said

    If the prompt message is wider than the widest element, then it will be cropped, since the width of the combo box is determined by the width of the widest element.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: