开发者

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

How to convert the getSelectedItem() from JComboBox to int or a开发者_JAVA技巧ny 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.


You can cast it to (String).

String value = (String) comboBox.getSelectedItem();


//compiled in netbeans

import java.awt.GridLayout;<br>
import javax.swing.JComboBox;<br>
import javax.swing.JOptionPane;<br>
import javax.swing.JPanel;<br>
import javax.swing.SwingUtilities;<br>

class TestCombo {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            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);
            }
        });
    }
}


String value = comboBox.getSelectedItem(comboBox.getSelectedIndex());

No casts are required.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜