0
我正在尋找一種方法來創建鏈接到jlist的搜索框,以便當用戶鍵入一個字符序列時,它將搜索並匹配到JList項目,然後突出顯示該項目。 我創建了一個jtextfield並添加了一個keylistener。 這部分代碼正常工作,但僅適用於用戶輸入的第一個字符。我正在嘗試將其擴展爲用戶鍵入的任意數量的字符。任何想法如何實現?謝謝你在前進搜索JList
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);
}
});
您不應該在文本組件上使用KeyListener,實際上應該幾乎不會使用KeyListeners時段。也許你想在JTextField的Document上使用DocumentListener。 –
請考慮使用單個列「JTable」。可以將一個['RowSorter'](http://docs.oracle.com/javase/7/docs/api/javax/swing/DefaultRowSorter.html)添加到表中,並且它也可以用作行過濾器。 –
對代碼塊使用一致的邏輯縮進。代碼的縮進旨在幫助人們理解程序流程。 –