简体   繁体   中英

Find anywhere in jList items?

I can find item in jlist with this code. But I want to find anywhere in item. How can I do this. Thanks a lot. (Sorry my English)

For example: I can find "New or San" but I want to find "York or Diago".

New York
San Diago

  jTextField1.addKeyListener(new KeyAdapter() {
        public void keyReleased(KeyEvent e) {
            String text = "" + e.getKeyChar();
            StringBuffer buffer = new StringBuffer(jTextField1.getText().substring(0, jTextField1.getText().length() - 1));
            buffer.append(text);
            int index = jList1.getNextMatch(buffer.toString(), 0, Position.Bias.Forward);
            jList1.setSelectedIndex(index);
        }
    });

getNextMatch checks if the given string exists at the start position passed as the second param. You can just traverse the jlist to find the index.

jTextField1.addKeyListener(new KeyAdapter() {
    public void keyReleased(KeyEvent e) {
        String text = "" + e.getKeyChar();
        StringBuffer buffer = new StringBuffer(jTextField1.getText().substring(0, jTextField1.getText().length() - 1));
        buffer.append(text);
        ListModel<String> model = jList1.getModel();
        int index; 
        for(int i = 0; i < model.getSize(); i++) {
            if(model.getElementAt(i).contains(buffer.toString())){
                index = i;
                break;
            }
        }

        jList1.setSelectedIndex(index);
    }
});

I believe the method available in JList only searches if the items start with a specific prefix.

public List<Integer> getMatches(ListModel listModel, String text){
List<Integer> indices = new List<Integer>();
for(int i = 0; i < listModel.getSize(); i++){
    if(listModel.getElementAt(i).contains(text)){
        indices.add(i);
    }
}
return indices;

}

The method above iterates the listmodel and checks if each element contains the text provided and returns the indices of matched items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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