0

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");
            }
        }
    });
Jess
  • 23,901
  • 21
  • 124
  • 145
  • 1
    Well you compare objects equality with `equals`.. `==` just compares reference if they pointing to the same object – nachokk Jan 13 '14 at 18:48

2 Answers2

5

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.

Community
  • 1
  • 1
nachokk
  • 14,363
  • 4
  • 24
  • 53
3
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");
    }
});
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • @assylias I do not understand your comment. Are you referring to me or the OP? I added the Swing tag of course. I intimated Swing from the use of `ItemListener`. Does Java-FX also use the `ItemListener`? – Andrew Thompson Jan 13 '14 at 19:04
  • for some reason I thought it was a JavaFX ComboBox but I was mistaken! In JavaFX it would be something like: `comboBox.addChangeListener(...)` – assylias Jan 13 '14 at 19:07
  • @assylias Aah.. I must admit I am not entirely sure it is Swing. It could be pure AWT for all I know. OP - For better help sooner, post an **[MCVE](http://stackoverflow.com/help/mcve).** – Andrew Thompson Jan 13 '14 at 19:09
  • Nice! Did you write that? It looks like MVCE == summarize(SSCCE)! – assylias Jan 13 '14 at 19:15
  • 1
    @assylias Thanks! It is based on [what I wrote](http://meta.stackexchange.com/a/215383/155831) (community WIKI answer). – Andrew Thompson Jan 13 '14 at 19:17
  • @assylias I actually just noticed it has become MCVT on that thread! ;) – Andrew Thompson Jan 13 '14 at 19:20
  • 1
    so now it will be `For better help sooner post a MCVT` ? – nachokk Jan 13 '14 at 19:42
  • 1
    @nachokk No.. for the moment I'm sticking with what it is seen at http://stackoverflow.com/help/mcve (I suspect the Wiki change will not be adopted). – Andrew Thompson Jan 13 '14 at 19:48