0
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Count extends JFrame implements ItemListener {

    private JComboBox box;
    private static String[] num = {"5", "6", "7", "8", "9", "10"};
    private static int size, i;

    public Count() {
        super("Count");
        setLayout(new FlowLayout());

        box = new JComboBox(num);
        box.addItemListener(this);
        add(box);
    }

    @Override
    public void itemStateChanged(ItemEvent e) {
        size = Integer.parseInt((String)box.getSelectedItem());
        for (i = 1; i <= size; i++) {
            System.out.print(" " + i);
        }
        System.out.println();

    }

    public static void main(String[] args) {
        Count a = new Count();
        a.setSize(200, 150);
        a.setVisible(true);
        a.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }
}

this code print from 1 to selected item

EX: if you select number 8 ,will print

1 2 3 4 5 6 7 8

BUT there is wrong

EX: when select number 8 ,will print

1 2 3 4 5 6 7 8

1 2 3 4 5 6 7 8

print twice, why?

BlueSky
  • 11
  • 3
  • Because `itemStateChanged` fires twice, as the state change 2 times change then select... If you look at the behavioral of `JComboBox` it took two steps. Open and select then close it – Ahmed Hamdy May 27 '14 at 16:52
  • possible duplicate of [Why is itemStateChanged on JComboBox is called twice when changed?](http://stackoverflow.com/questions/330590/why-is-itemstatechanged-on-jcombobox-is-called-twice-when-changed) – ryvantage May 27 '14 at 16:58

3 Answers3

2

Here the itemStateChanged triggers 2 times. But if you can change the itemStateChanged() method like this, you can filter out only one state out of 2 states

 public void itemStateChanged(ItemEvent e) {
        size = Integer.parseInt((String)box.getSelectedItem());
        if (e.getStateChange() == ItemEvent.SELECTED){
            for (i = 1; i <= size; i++) {
                System.out.print(" " + i);
            }
            System.out.println();
        }
    }
Tharindu Kumara
  • 4,398
  • 2
  • 28
  • 46
1

Because the item has two states: selected or deselected So itemStateChanged fired twice.

Please refer to this question Why is itemStateChanged on JComboBox is called twice when changed?

Community
  • 1
  • 1
Ahmed Hamdy
  • 2,547
  • 1
  • 17
  • 23
1

Here is the fix for your problem.

 @Override
    public void itemStateChanged(ItemEvent e) {

      if (e.getStateChange() == ItemEvent.SELECTED) {
        size = Integer.parseInt((String)box.getSelectedItem());
        for (i = 1; i <= size; i++) {
            System.out.print(" " + i);
        }
        System.out.println();
      }
    }
Viorel Florian
  • 594
  • 9
  • 29