Question

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");
            }
        }
    });
Was it helpful?

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.

OTHER TIPS

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

Is probably better written as:

comboBox.addItemListener(new ItemListener() {
    public void itemStateChanged(ItemEvent arg0)
    {
        tfbf.setText(comboBox.getSelectedItem() + " selected");
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top