Search code examples
javastringswingjcomboboxstring-comparison

Write something to text field when any item from combobox is selected


I want to write something to a text field when I select any item from combo box. But I couldn't do this.

Java code:

comboBox.addItemListener(new ItemListener() {
    public void itemStateChanged(ItemEvent arg0) {
            if(comboBox.getSelectedItem()=="apple") {
                tfbf.setText("apple selected");
            }
        }
    });

Solution

  • As you don't provide any valid example . You compare object observational equality with equals(..) not with ==.

    "apple".equals(comboBox.getSelectedItem())
    

    Read more How do I compare strings in Java?

    == tests for reference equality.

    .equals() tests for value equality.