2
jbox.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            for (int x = 0; x < string.length; x++) {
                if (jbox.getSelectedItem() == string[x]) {
                    System.out.println(string[x]);
                }}}});

When I run this it prints twice. What have I done wrong? (sorry for my bad english)

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
roboticonx8
  • 39
  • 1
  • 11
  • Don't forget to use the search capabilities of this site. For instance [this search](http://stackoverflow.com/search?q=%5Bjava%5D+%5Bswing%5D+itemlistener+twice) will get you helpful results. – Hovercraft Full Of Eels Jan 24 '15 at 14:35

1 Answers1

2

The ItemListener will trip twice since one item is deselected and another is selected. Consider using an ActionListener.

Note though that you shouldn't compare Strings using == or !=. Use the equals(...) or the equalsIgnoreCase(...) method instead. Understand that == checks if the two objects are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. So instead of

if (jbox.getSelectedItem() == string[x]) {

do

if (jbox.getSelectedItem().equals(string[x])) {
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373