Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting the getSelectedItem() from JComboBox to int or any other thing

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?

like image 986
aps Avatar asked Jan 20 '23 06:01

aps


2 Answers

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.

like image 170
Andrew Thompson Avatar answered Jan 30 '23 21:01

Andrew Thompson


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.

like image 43
Asaph Avatar answered Jan 30 '23 22:01

Asaph