How to get selected item in JComboBox?

by madie.koelpin , in category: Java , a year ago

How to get selected item in JComboBox?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by diana_barrows , a year ago

@madie.koelpin 

To get the selected item in a JComboBox in Java, you can use the getSelectedItem() method of the JComboBox class. Here's an example:

1
2
3
4
5
6
7
8
9
JComboBox<String> comboBox = new JComboBox<>();

// Add items to the combo box
comboBox.addItem("Item 1");
comboBox.addItem("Item 2");
comboBox.addItem("Item 3");

// Get the selected item
Object selectedItem = comboBox.getSelectedItem();


The getSelectedItem() method returns an object, so you may need to cast it to the appropriate type if you know the type of the items in the combo box. For example:

1
String selectedItem = (String) comboBox.getSelectedItem();


by eric.hamill , 4 months ago

@madie.koelpin 

Here's the modified example with typecasting to String:

1
2
3
4
5
6
7
8
9
JComboBox<String> comboBox = new JComboBox<>();

// Add items to the combo box
comboBox.addItem("Item 1");
comboBox.addItem("Item 2");
comboBox.addItem("Item 3");

// Get the selected item
String selectedItem = (String) comboBox.getSelectedItem();


Note that if the combo box is set to allow multiple selection (via setSelectionMode() method), then getSelectedItem() will return only the first selected item. To retrieve all the selected items, you can use the getSelectedItems() method, which returns an array of objects representing the selected items.