自动建议的组合框

huangapple go评论62阅读模式
英文:

Auto-suggestion ComboBox

问题

我有一个JComboBox,这个JComboBox有很多项。我想在JComboBox上添加“自动建议”功能。

就像这样:我有3个项,“Artpop”,“Born This Way”和“Chromatica”。如果我键入“Way”,然后自动完成会选择“Born This Way”项。如果我键入“matica”,然后自动完成会选择“Chromatica”项。

我在StackOverflow上寻找过,但所有的答案都已过时(我正在使用Swing,而答案是为AWT编写的。当我尝试答案时,出现了多个错误)。

如何在Swing JComboBox上实现自动建议?

英文:

I have a JComboBox and the JComboBox has so many items. I want to add “auto-suggestion” feature on the JComboBox.

Like this: I have 3 items, “Artpop”, “Born This Way”, and “Chromatica”. If I type “Way” then the autocomplete selects the “Born This Way" item. If I type "matica" then the autocomplete selects the "Chromatica" item.

I was looking for it on StackOverflow, but all the answers are outdated (I'm using Swing, while the answers are for AWT. When I do the answers, I've got several errors).

How to make auto-suggestion Swing JComboBox?

答案1

得分: 0

以下是翻译好的内容:

需要一个 JTextField 和一个 JComboBox 来创建自动建议的组合框。

这里是我准备的一个示例。不幸的是,GUI 图片不能正确显示 JComboBox。

自动建议的组合框

我创建了一个简单的 GUI,其中包含一个 JTextField 和一个 JComboBox

当您在 JTextField 中输入一个字符时,JComboBox 的选项会被减少到包含该字符的 Strings。搜索不区分大小写。如果您输入一个 w,它将返回所有带有 wWStrings

以下是我使用的完整可运行代码。

import java.awt.BorderLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class AutoSuggestionExample implements Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new AutoSuggestionExample());
    }

    private DefaultComboBoxModel<String> comboBoxModel;

    private JTextField autoSuggestionField;

    private List<String> masterList;

    public AutoSuggestionExample() {
        String[] masterList = { "Artpop", "Born This Way", "Chromatica" };
        this.masterList = Arrays.asList(masterList);
        this.comboBoxModel = new DefaultComboBoxModel<>(masterList);
    }

    @Override
    public void run() {
        JFrame frame = new JFrame("Auto Suggestion Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(createMainPanel(), BorderLayout.CENTER);

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    private JPanel createMainPanel() {
        JPanel panel = new JPanel();

        autoSuggestionField = new JTextField(20);
        autoSuggestionField.addKeyListener(new AutoSuggestionListener());
        panel.add(autoSuggestionField);

        JComboBox<String> comboBox = new JComboBox<>(comboBoxModel);
        comboBox.setSelectedIndex(0);
        panel.add(comboBox);

        return panel;
    }

    public List<String> createSelectedList(String search) {
        if (search.isEmpty()) {
            return masterList;
        }

        search = search.toLowerCase();
        List<String> selectedList = new ArrayList<>();
        for (String s : masterList) {
            if (s.toLowerCase().contains(search)) {
                selectedList.add(s);
            }
        }

        return selectedList;
    }

    public void updateComboBox(List<String> selectedList) {
        comboBoxModel.removeAllElements();
        comboBoxModel.addAll(selectedList);
        if (selectedList.size() > 0) {
            comboBoxModel.setSelectedItem(selectedList.get(0));
        }
    }

    public class AutoSuggestionListener extends KeyAdapter {

        @Override
        public void keyPressed(KeyEvent event) {
            String text = autoSuggestionField.getText() + event.getKeyChar();
            updateComboBox(createSelectedList(text));
        }

    }
}
英文:

It takes a JTextField and a JComboBox to create an auto-suggestion combo box.

Here's an example I put together. Unfortunately, the GUI picture doesn't display the JComboBox correctly.

自动建议的组合框

I created a simple GUI with a JTextField and a JComboBox.

When you type a character in the JTextField, the JComboBox options are reduced to the Strings that contain that character. The search is not case sensitive. If you type a w, it will return all Strings with a w or a W.

Here's the complete, runnable code I used.

import java.awt.BorderLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class AutoSuggestionExample implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new AutoSuggestionExample());
}
private DefaultComboBoxModel&lt;String&gt; comboBoxModel;
private JTextField autoSuggestionField;
private List&lt;String&gt; masterList;
public AutoSuggestionExample() {
String[] masterList = { &quot;Artpop&quot;, &quot;Born This Way&quot;, &quot;Chromatica&quot; };
this.masterList = Arrays.asList(masterList);
this.comboBoxModel = new DefaultComboBoxModel&lt;&gt;(masterList);
}
@Override
public void run() {
JFrame frame = new JFrame(&quot;Auto Suggestion Example&quot;);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createMainPanel(), BorderLayout.CENTER);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createMainPanel() {
JPanel panel = new JPanel();
autoSuggestionField = new JTextField(20);
autoSuggestionField.addKeyListener(new AutoSuggestionListener());
panel.add(autoSuggestionField);
JComboBox&lt;String&gt; comboBox = new JComboBox&lt;&gt;(comboBoxModel);
comboBox.setSelectedIndex(0);
panel.add(comboBox);
return panel;
}
public List&lt;String&gt; createSelectedList(String search) {
if (search.isEmpty()) {
return masterList;
}
search = search.toLowerCase();
List&lt;String&gt; selectedList = new ArrayList&lt;&gt;();
for (String s : masterList) {
if (s.toLowerCase().contains(search)) {
selectedList.add(s);
}
}
return selectedList;
}
public void updateComboBox(List&lt;String&gt; selectedList) {
comboBoxModel.removeAllElements();
comboBoxModel.addAll(selectedList);
if (selectedList.size() &gt; 0) {
comboBoxModel.setSelectedItem(selectedList.get(0));
}
}
public class AutoSuggestionListener extends KeyAdapter {
@Override
public void keyPressed(KeyEvent event) {
String text = autoSuggestionField.getText() + event.getKeyChar();
updateComboBox(createSelectedList(text));
}
}
}

答案2

得分: 0

如Andrew Thompson所评论:“当一个组合框处于焦点状态,并且用户键入包含在其中的某个项目的首字母时,该项目将被选中”
这种行为在公共方法JComboBox.selectWithKeyChar(char keyChar)中定义。
您可以扩展JComboBox以覆盖selectWithKeyChar(char keyChar)方法以定义不同的行为。

英文:

As Andrew Thompson commented: "When a combo box is in focus and the user types the first letters of an item it contains, that item will become selected" <br/>
This behavior is defined in the public method JComboBox.selectWithKeyChar(char keyChar).
You can extend JComboBox to override selectWithKeyChar(char keyChar) to define a different behavior.

huangapple
  • 本文由 发表于 2020年10月22日 09:48:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/64474078.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定