java - 在 jCombobox 上实现自动完成

标签 java swing autocomplete jcombobox listcellrenderer

我有一个包含国家/地区列表的 jCombobox。它由数据库填充,包含国家 ID 和国家名称,因此组合框中仅显示国家/地区名称,但当单击某个值时,它将返回所选国家/地区的 ID。我已经成功地使用自定义 ListCellRenderer 实现了这一点。

public class UGIS_ComboboxRenderer extends JLabel implements ListCellRenderer {

@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
    Object[] itemData = (Object[]) value;
    setText((String) itemData[1]);
    return this;
}
}

单个国家/地区对象看起来与此类似

Object[] country1 = new Country(){1, "United Kingdom"}

我有一个像上面这样的对象数组列表,并将它们添加到组合框中,如下所示

for (Object[] temp : countrylist) {
        jComboBox1.addItem(temp); 
                }

现在我想要的是为此组合框提供自动完成功能,以便用户可以键入国家/地区名称并有效导航到组合框列表中的“感兴趣的区域”。关于如何实现这一目标有什么想法吗?

最佳答案

Now what I want is to have an AutoComplete feature for this combobox so that the user can type the country name and efficiently navigate to the "Area of interest" in the combo box list

这是 JComboBox 的默认功能。当您键入字符时,选择将移动到列表中包含这些字符的项目。

It is populated by a database and contains countryID and countryName, So only the country name is shown in the combo box but when clicked on a value it will return the selected country's id. I have managed to achieve this using custom ListCellRenderer.

自定义渲染器会破坏上述默认功能。

参见Combo Box With Custom Renderer一个也实现 KeySelectionManager 的解决方案,因此键盘选择功能仍然可以工作。

关于java - 在 jCombobox 上实现自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21259461/

相关文章:

java - 使用适用于 32 位和 64 位 Windows 的 log4j2 配置进行 Windows 事件日志记录

java - 模态 JDialog 的 1x1 维度

java - 显示 JFrame 作为 JButton 单击的结果?

javascript - 在 Jquery 中选择后如何获取列表框项目文本?

javascript - 如何将 HTML 无序列表转换为 jQuery 自动完成?

java - Java中通过正则表达式从字符串中提取数字

java - 编写数组声明字符串

java - 当我突破内部 if 时,为什么我的消息会打印两次?

java - 完成操作后关闭 Swing 对话框

ruby-on-rails - 你如何从另一个模型自动完成?