JComboBox,itemStateChanged

时间:2014-05-27 16:48:56

标签: java jframe jcombobox

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);

    }
}

此代码从1打印到选定项目

EX: 如果您选择数字8,将打印

1 2 3 4 5 6 7 8

但是有错误的

EX: 当选择数字8时,将打印

1 2 3 4 5 6 7 8

1 2 3 4 5 6 7 8

打印两次,为什么?

3 个答案:

答案 0 :(得分:2)

此处itemStateChanged触发2次。但是,如果您可以像这样更改itemStateChanged()方法,则只能过滤出2种状态中的一种状态

 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();
        }
    }

答案 1 :(得分:1)

因为该项目有两种状态:选择取消选择所以itemStateChanged被解雇两次。

请参阅此问题Why is itemStateChanged on JComboBox is called twice when changed?

答案 2 :(得分:1)

以下是您问题的解决方法。

 @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();
      }
    }