Hi;
I have a code below that should search a string and if the string is found should highlight and select the string on the JList:
import java.awt.BorderLayout;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.StringTokenizer;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.text.Position;
public class ListSearch extends JFrame {
private JList list;
private JTextField field;
private DefaultListModel listModel;
private StringTokenizer token;
private BufferedReader br;
private StringBuffer allText;
public ListSearch() {
super("ListSeach");
try {
br = new BufferedReader(new FileReader(new File("com/employee.txt")));
String text = null;
allText = new StringBuffer();
while((text = br.readLine()) != null) {
allText.append(text + "\r\n");
}
token = new StringTokenizer(allText.toString());
listModel = new DefaultListModel();
while(token.hasMoreTokens()) {
listModel.addElement(token.nextToken());
}
} catch(Exception e) {
e.printStackTrace();
}
list = new JList(listModel);
field = new JTextField();
getContentPane().add(field, BorderLayout.NORTH);
getContentPane().add(new JScrollPane(list), BorderLayout.CENTER);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(400, 300);
setLocationRelativeTo(null);
setVisible(true);
field.addKeyListener(new KeyAdapter() {
public void keyReleased(KeyEvent e) {
char text = "" + e.getKeyChar();
StringBuffer buffer = new StringBuffer();
buffer.append(text);
int index = list.getNextMatch(buffer, 0, Position.Bias.Forward);
System.out.println(index);
list.setSelectedIndex(index);
}
});
}
public static void main(String[] args) {
ListSearch h = new ListSearch();
}
}
My sample text is:
Employee.Arnold.James
Employee.Arnold.Warlburg
Employee.Arnold.Seen
The problem is when the user tries to type any on the text it only selects the 1st one? Can anyone help