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打印到所选项目

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

1 2 3 4 5 6 7 8

但是有错

例如:
选择数字8时,将打印

1 2 3 4 5 6 7 8

1 2 3 4 5 6 7 8

打印两次,为什么?

最佳答案

此处itemStateChanged触发两次。但是,如果您可以像这样更改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();
        }
    }

关于java - JComboBox,itemStateChanged,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23894811/

10-13 23:50