【问题标题】:How do I change the selection of a combo box mid program?如何更改组合框中间程序的选择?
【发布时间】:2021-08-04 04:20:43
【问题描述】:

我在摆动面板上有一个组合框。我将索引设置为默认索引,但基于文本框的输入,我想更改组合框选择。因此,如果用户输入 2,我希望它在组合框中选择第二个选项。

有人知道我需要哪条线路吗?我试过了

combobox.setSelectedIndex(2);

但这似乎不起作用。

【问题讨论】:

  • 发布您的minimal reproducible example 以证明问题。因此,您只需要一个带有组合框、文本字段和 ActionListener 的 JFrame。一旦你得到这个工作,然后你修复你的真实应用程序。

标签: java swing jcombobox


【解决方案1】:

根据JComboBox docs,索引是从0开始的,所以如果你想设置第二个项目,那就是索引1。

因此,假设您已经进行了一些验证以确保输入的数字在 [1, numOptions] 范围内,那么您可以安全地调用:

combobox.setSelectedIndex(enteredNumber - 1);

类似:

// Assume this is initialized by getting from edit text field where
// the entered number is a human-understandable index starting with 1.
int enteredNumber;
if (enteredNumber > 0 && enteredNumber <= combobox.getItemCount()) {
    combobox.setSelectedIndex(enteredNumber - 1);
}

【讨论】:

  • 谢谢,但这不会改变组合框的选择,我已经尝试用数字对其进行硬编程,但仍然没有改变
  • 如果在调用 setSelectedIndex 后立即调用 combobox.repaint() 会发生什么?你确定你是从 UI 线程调用 setSelectedIndex 吗?
猜你喜欢
  • 1970-01-01
  • 2011-09-19
  • 1970-01-01
  • 1970-01-01
  • 2012-01-30
  • 1970-01-01
  • 2022-01-23
相关资源
最近更新 更多