如何知道你在JComboBox中选择了什么

时间:2015-10-15 05:24:45

标签: java swing user-interface jcombobox

我在java中创建了一个Basic计算器应用程序,它有2个JTextFields和1个JComboBox。我想知道是否有办法让JButton检测你在JComboBox中选择的内容,当我用文本字段做它时,它看起来像这样

 static String divide = "/";

if (n == JOptionPane.OK_OPTION) {
                if (symbol.getText().equals(divide)){
                 <code>
              }
         }

有没有类似的方法用JComboBoxs做到这一点?

String[] symbols = {times, minus, plus, divide};

这是JComboBox的内容代码。

2 个答案:

答案 0 :(得分:3)

您可以使用方法.getSelectedItem()从JComboBox中获取所选项目。

假设你有String [] symbols = {times,minus,plus,divide};作为构造JComboBox时的输入(参见构造函数JComboBox(E[] items)

JComboBox jcb = new JComboBox(symbols);

//you will see the string you selected
System.out.println(jcb.getSelectedItem());

答案 1 :(得分:1)

也许使用动作监听器

String[] quantities1 = {"/","+"};
JComboBox comboBox = new JComboBox(quantities1);
        comboBox.addActionListener(
                new ActionListener(){
                    public void actionPerformed(ActionEvent e){
                        //do stuff when a section is performed
                        //you can use comboBox.getSelectedItem() to get the selected value
                    }
                }            
        );