Akinwale Agbaje
Akinwale Agbaje

Reputation: 315

Getting int value from combo box in Java

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?

Upvotes: 0

Views: 21928

Answers (2)

ewan.chalmers
ewan.chalmers

Reputation: 16235

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:

int s_n = (Integer) jComboBoxSN.getSelectedItem();

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:

Integer i = (Integer)jComboBoxSN.getSelectedItem();
if (i != null) {
    int s_n = i;  // or s_n = i.intValue();
}

However, I think something like this would be more suitable:

    final JTextArea text = new JTextArea();
    JComboBox combo = new JComboBox();
    combo.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                // assume single selection
                int i = (Integer)e.getItemSelectable().getSelectedObjects()[0];
                text.setText("Selected [" + i + "]");
            }
        }
    });

Upvotes: 3

Mat
Mat

Reputation: 206689

If what you stored in the combo box are Integers, then this is acceptable. Otherwise it is not.

You'll get the object you added at the selected position with getSelectedItem(). If you want the index of that item in the combo box, use getSelectedIndex() (which returns an int).

(Note: without knowing what class of objects you put in there, it's a bit hard to guess what you actually want out of it.)

Upvotes: 1

Related Questions