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();
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you have only put (non-null)
Stringreferences 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
nullvalues (still without casting) you may consider a third option: