简体   繁体   English

搜索一个JList

[英]Search for a JList

I am looking for a way to create a searchbox linked to a jlist, so that when the user types a sequence of characters, it will search and match to a JList item, then highlight that item. 我正在寻找一种创建链接到jlist的搜索框的方法,以便当用户键入字符序列时,它将搜索并匹配到JList项目,然后突出显示该项目。 I have created a jtextfield and added a keylistener. 我创建了一个jtextfield并添加了一个侦听器。 This part of the code works properly, but only for the first character the user types. 这部分代码可以正常工作,但只适用于用户键入的第一个字符。 I am trying to expand this to any number of characters the user types. 我正在尝试将此扩展为用户键入的任意数量的字符。 Any ideas how to achieve that? 有什么想法要实现吗? Thank you in advance 先感谢您

String[] feedStrings = {"aaa", "abc", "opo","oiuu"}

JList feedList = new JList(feedStrings);

feedList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
feedList.setLayoutOrientation(JList.VERTICAL);

feedList.setVisibleRowCount(4);


                JTextField searchbox = new JTextField();
        searchbox.setColumns(8);
        searchbox.setVisible(true);


        searchbox.addKeyListener(new KeyAdapter() {
                 public void keyReleased(KeyEvent e) {

                  String text = "" + e.getKeyChar();
                  StringBuffer buffer = new StringBuffer();
                  buffer.append(text);
                  String strbuf = buffer.toString();

                  int index = feedList.getNextMatch(strbuf, 0, Position.Bias.Forward);
                  System.out.println(index);
                  feedList.setSelectedIndex(index);
            }
      });

but only for the first character the user types. 但仅针对用户输入的第一个字符。 I am trying to expand this to any number of characters the user types 我正在尝试将此扩展为用户键入的任意数量的字符

Just use the text from the Document. 只需使用文档中的文本即可。 That is another reason to be using a DocumentListener and NOT a KeyListener. 这是使用DocumentListener而不是KeyListener的另一个原因。

Although I like the suggestion to use a JTable. 尽管我喜欢使用JTable的建议。 The Swing tutorial on How to Use Tables even has a working example that shows you exactly how to do this. 有关How to Use Tables的Swing教程甚至提供了一个有效的示例,向您展示了如何执行此操作。 You can find the link to the tutorial by reading the JTable API. 您可以通过阅读JTable API来找到本教程的链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM