[英]JComboBox ,itemStateChanged
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 此代码从1打印到所选项目
EX: if you select number 8 ,will print 例如:如果选择数字8,将打印
1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8
BUT there is wrong 但是有错
EX: when select number 8 ,will print 例如:选择数字8时,将打印
1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8
print twice, why? 打印两次,为什么?
Here the itemStateChanged triggers 2 times. 此处itemStateChanged触发两次。 But if you can change the itemStateChanged() method like this, you can filter out only one state out of 2 states
但是,如果您可以像这样更改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();
}
}
Because the item has two states: selected or deselected So itemStateChanged
fired twice. 因为项目具有两种状态:已选择或取消选择,所以
itemStateChanged
触发了两次。
Please refer to this question Why is itemStateChanged on JComboBox is called twice when changed? 请参考此问题。 为什么更改JComboBox上的itemStateChanged两次?
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.