Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding items to a JComboBox

Tags:

I use a combo box on panel and as I know we can add items with the text only

    comboBox.addItem('item text'); 

But some times I need to use some value of the item and item text like in html select:

    <select><option value="item_value">Item Text</option></select> 

Is there any way to set both value and title in combo box item?

For now I use a hash to solve this issue.

like image 220
Nickolay Kondratenko Avatar asked Jul 26 '13 17:07

Nickolay Kondratenko


People also ask

How do I add items to a comboBox in Java?

Add the ComboItem to your comboBox. comboBox. addItem(new ComboItem("Visible String 1", "Value 1")); comboBox.

How do I make JComboBox not editable?

u can make ur jcombobox uneditable by calling its setEnabled(false). A JComboBox is unEditable by default. You can make it editable with the setEditable(boolean) command. If you are talking about enabled or disabled you can set that by the setEnabled(boolean) method.

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.


2 Answers

Wrap the values in a class and override the toString() method.

class ComboItem {     private String key;     private String value;      public ComboItem(String key, String value)     {         this.key = key;         this.value = value;     }      @Override     public String toString()     {         return key;     }      public String getKey()     {         return key;     }      public String getValue()     {         return value;     } } 

Add the ComboItem to your comboBox.

comboBox.addItem(new ComboItem("Visible String 1", "Value 1")); comboBox.addItem(new ComboItem("Visible String 2", "Value 2")); comboBox.addItem(new ComboItem("Visible String 3", "Value 3")); 

Whenever you get the selected item.

Object item = comboBox.getSelectedItem(); String value = ((ComboItem)item).getValue(); 
like image 95
JBuenoJr Avatar answered Oct 22 '22 12:10

JBuenoJr


You can use any Object as an item. In that object you can have several fields you need. In your case the value field. You have to override the toString() method to represent the text. In your case "item text". See the example:

public class AnyObject {      private String value;     private String text;      public AnyObject(String value, String text) {         this.value = value;         this.text = text;     }  ...      @Override     public String toString() {         return text;     } }  comboBox.addItem(new AnyObject("item_value", "item text")); 
like image 36
Ataul Ahmad Avatar answered Oct 22 '22 12:10

Ataul Ahmad