Dragon4c3
Dragon4c3

Reputation: 77

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.

Upvotes: 2

Views: 1080

Answers (2)

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

Upvotes: 3

Achintha Gunasekara
Achintha Gunasekara

Reputation: 1165

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

Upvotes: 1

Related Questions