How to convert the getSelectedItem() from JComboBox to int or any other thing? Even converting to string isn't working. Eclipse says " Type mismatch: cannot convert from Object to String" or int or whatever. Any way to achieve this?
It works just fine here with objects.
import java.awt.*;
import javax.swing.*;
class TestCombo {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Integer[] numbers = {1,2,3};
String[] names = {"Ben", "Jill", "Peter"};
JComboBox numberCombo = new JComboBox(numbers);
JComboBox nameCombo = new JComboBox(names);
JPanel p = new JPanel(new GridLayout(0,1,3,3));
p.add(numberCombo);
p.add(nameCombo);
JOptionPane.showMessageDialog(null, p);
Integer chosenNumber = (Integer)numberCombo.getSelectedItem();
System.out.println("Chosen Number: " + chosenNumber);
String chosenName = (String)nameCombo.getSelectedItem();
System.out.println("Chosen Name: " + chosenName);
}
});
}
}
Typical output:
Chosen Number: 2
Chosen Name: Peter
Press any key to continue . . .
I agree strongly with the comment by LBFF. You need to go back to the basics.
The answer really depends on what kind of items you placed into the JComboBox
to begin with. Whatever you put into it (eg. with addItem()
or insertItemAt()
) is what you can get out of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With