gpt4 book ai didi

java - JComboBox,itemStateChanged

转载 作者:行者123 更新时间:2023-12-01 18:31:40 25 4
gpt4 key购买 nike

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 次。但是,如果您可以像这样更改 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com