Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preferred way of getting the selected item of a JComboBox

Tags:

java

swing

HI,

Which is the correct way to get the value from a JComboBox as a String and why is it the correct way. Thanks.

String x = JComboBox.getSelectedItem().toString();

or

String x = (String)JComboBox.getSelectedItem();
like image 348
user489041 Avatar asked Feb 10 '11 20:02

user489041


People also ask

How do you check what is selected in a JComboBox?

You can use JComboBox#getSelectedIndex , which will return -1 if nothing is selected or JComboBox#getSelectedItem which will return null if nothing is selected.

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.

What is JComboBox in Java?

The class JComboBox is a component which combines a button or editable field and a drop-down list.


3 Answers

If you have only put (non-null) String references in the JComboBox, then either way is fine.

However, the first solution would also allow for future modifications in which you insert Integers, Doubless, LinkedLists etc. as items in the combo box.

To be robust against null values (still without casting) you may consider a third option:

String x = String.valueOf(JComboBox.getSelectedItem()); 
like image 91
aioobe Avatar answered Sep 19 '22 17:09

aioobe


The first method is right.

The second method kills kittens if you attempt to do anything with x after the fact other than Object methods.

like image 30
James Avatar answered Sep 21 '22 17:09

James


String x = JComboBox.getSelectedItem().toString();

will convert any value weather it is Integer, Double, Long, Short into text on the other hand,

String x = String.valueOf(JComboBox.getSelectedItem());

will avoid null values, and convert the selected item from object to string

like image 44
androminor Avatar answered Sep 20 '22 17:09

androminor