Search code examples
javaswinguser-interfacejcombobox

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.


Solution

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