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.
Add the ComboItem to your comboBox. comboBox. addItem(new ComboItem("Visible String 1", "Value 1")); comboBox.
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.
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.
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();
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With