简体   繁体   中英

How to know what you selected in the JComboBox

I am making a Basic calculator app in java which has 2 JTextFields and 1 JComboBox. What i want to know if there is a way to let a JButton detect what you selected in the JComboBox, when i did it with the text field it looked something like this

 static String divide = "/";

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

So is there a similar way to do this with JComboBoxs??

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

That's the JComboBox's content code.

You can get selected item from JComboBox with method .getSelectedItem() .

Say you have String[] symbols = {times, minus, plus, divide}; as an input when constructing JComboBox (see constructor JComboBox(E[] items) )

JComboBox jcb = new JComboBox(symbols);

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

Perhaps use action listener

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM