gpt4 book ai didi

java - 可编辑的 JComboBox

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:35:01 25 4
gpt4 key购买 nike

我有可编辑的 JComboBox 并希望从它的输入中添加值,例如当我在 JComboBox 中键入内容并按回车键时我希望该文本出现在 JComboBox 列表:

public class Program extends JFrame 
implements ActionListener {
private JComboBox box;

public static void main(String[] args) {
new Program().setVisible(true);
}

public Program() {
super("Text DEMO");
setSize(300, 300);
setLayout(new FlowLayout());
Container cont = getContentPane();
box = new JComboBox(new String[] { "First", "Second", "..." });
box.setEditable(true);
box.addActionListener(this);
cont.add(box);
}

@Override
public void actionPerformed(ActionEvent e) {
box.removeActionListener(this);
box.insertItemAt(box.getSelectedItem(), 0);
box.addActionListener(this);
}
}

不幸的是,当我按下回车键时,插入了两个值而不是一个值。

为什么?

最佳答案

来自API对于 JComboBox :

The ActionListener will receive an ActionEvent when a selection has been made. If the combo box is editable, then an ActionEvent will be fired when editing has stopped.

因此,您的 ActionListener 被调用了两次。

要仅在编辑时将项目添加到 JComboBox,您可以像这样检查正确的 ActionCommand:

@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("comboBoxEdited")) {
//code
}
}

编辑(-> 事件派发线程)

正如 trashgod 已经提到的,您还应该仅在事件调度线程中创建和显示您的框架:

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new Program().setVisible(true);
}
});
}

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

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