【发布时间】:2014-05-27 16:48:55
【问题描述】:
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触发了两次,因为状态更改了 2 次然后选择...如果您查看JComboBox的行为,它需要两个步骤。打开并选择然后关闭它 -
@BlueSky 不客气 :)