I was struggling to get int values from a column in a database into a combo box, so that once selected the values would print out in a textbox when I deviced this solution:
private void jComboBoxSNActionPerformed(java.awt.event.ActionEvent evt) {
JComboBox jComboBoxSN = (JComboBox) evt.getSource();
int s_n = (Integer) jComboBoxSN.getSelectedItem();
System.out.println("Number: " + s_n);
}
I want to know, this acceptable programming or bad programming?
Unless you are certain that your combo box cannot contain null values (and this is uncertain if you are loading the values from a database), then the code you have shown is not safe. This line:
will result in a NullPointerException if executed on a null item. (Auto-unboxing a null primitive wrapper is a NullPointerException).
An alternative would be to check for null before converting Integer to int:
However, I think something like this would be more suitable: