将getSelectedItem()从JComboBox转换为int或任何其他东西

时间:2011-07-11 01:31:55

标签: java swing jcombobox

如何将getSelectedItem()从JComboBox转换为int或任何其他东西?即使转换为字符串也无效。 Eclipse说“类型不匹配:无法从Object转换为String”或int或其他。有没有办法实现这个目标?

5 个答案:

答案 0 :(得分:5)

这里的对象很好用。

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);
            }
        });
    }
}

典型输出:

Chosen Number: 2
Chosen Name: Peter
Press any key to continue . . .

我同意LBFF的评论。你需要回到基础。

答案 1 :(得分:3)

答案实际上取决于您在JComboBox开始使用的项目类型。无论你投入什么(例如,使用addItem()insertItemAt()),你都可以得到它。

答案 2 :(得分:0)

您可以将其投射到(String)

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

答案 3 :(得分:0)

//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);
            }
        });
    }
}

答案 4 :(得分:0)

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

不需要演员表。