Reputation: 83
I'm just new learning OOP sorry for this basic post. I don't know why it returns me a null when I'm trying to get the value of the selected item in my JComboBox
.
public class AddEmployee extends javax.swing.JInternalFrame{
public AddEmployee()
{
initComponents();
this.setSize(1100,500);
setMonths();
setJComboBoxProperties();
check();
}
private void setMonths()
{
String[] monthsObj = {"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"};
DefaultComboBoxModel monthsModel = new DefaultComboBoxModel(monthsObj);
cbMonths.setModel((ComboBoxModel)monthsModel);
}
private void setJComboBoxProperties()
{
cbMonths.setSelectedIndex(-1);
}
private String check()
{
String cb = (String)cbMonths.getSelectedItem();
System.out.println(cb);
return cb;
}
}
I cast the String cb
so it won't give me a null. But I'm trying to check out the selected item but it gives me null.
Upvotes: 3
Views: 4957
Reputation: 12067
You're calling cbMonths.setSelectedIndex(-1);
. This sets no item (null
) as the selected item, as per the documentation.
Until the user changes the selection, getSelectedItem()
will always return null
. This is the correct, documented behaviour.
Upvotes: 3
Reputation: 69460
Call setSelectedItem
after initialize the Combobox. See the documentation.
DefaultComboBoxModel monthsModel = new DefaultComboBoxModel(monthsObj);
monthsModel.setSelectedItem('September');
Upvotes: 2