我正在寻找一种创建链接到jlist的搜索框的方法,以便当用户键入字符序列时,它将搜索并匹配到一个JList项,然后突出显示该项。我创建了一个jtextfield并添加了一个keylistener。代码的这一部分正常工作,但只适用于用户类型的第一个字符。我试图将其扩展到用户输入的任意数量的字符。有什么办法可以做到吗?提前谢谢你
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);
}
});发布于 2014-01-19 04:04:15
但只对第一个字符的用户类型。我试图将其扩展到用户键入的任意数量的字符。
只需使用文档中的文本。这是使用DocumentListener而不是KeyListener的另一个原因。
虽然我喜欢使用JTable的建议。关于How to Use Tables的Swing教程甚至有一个工作示例,向您展示了如何做到这一点。您可以通过阅读JTable API找到到本教程的链接。
https://stackoverflow.com/questions/21211964
复制相似问题