Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JComboBox: want first entry to be blank entry

I have a jcombobox which values come from a list. I want to first value to be blank from dropdown list. The way I approached it was by putting new object of the list type in first as example shows :

 final List<Object> list = getObjectsList();
  list.add(new Object()); 

But this results in null pointer and if do

list.add(null);

this solves the issue but then gives me another prob elsewhere with a Comparator method. So any work a rounds would be great thanks.

like image 699
daverocks Avatar asked Jun 08 '11 08:06

daverocks


People also ask

How does JComboBox work?

JComboBox is a part of Java Swing package. JComboBox inherits JComponent class . JComboBox shows a popup menu that shows a list and the user can select a option from that specified list . JComboBox can be editable or read- only depending on the choice of the programmer .

What is the difference between JList and JComboBox?

A JComboBox is a component that displays a drop-down list and gives users options that we can select one and only one item at a time whereas a JList shows multiple items (rows) to the user and also gives an option to let the user select multiple items.

Which event gets generated when you select an item from a JComboBox?

The combo box fires an action event when the user selects an item from the combo box's menu.


2 Answers

You can also set the selected index to -1 after the items have been added, but before the event listener.

    JcomboBox.setSelectedIndex(-1);

This solution will work better if your JcomboBox uses generics.

like image 178
user1494530 Avatar answered Sep 21 '22 15:09

user1494530


Doesn't JComboBox.insertItemAt("", 0); work for you? You need to add validation for the blank entry too

like image 32
qwerty Avatar answered Sep 17 '22 15:09

qwerty