troubleshooting Question

Search in JList

Avatar of rajah_mohammed
rajah_mohammed asked on
2 Comments1 Solution3201 ViewsLast Modified:

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.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() {
            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()) {
            } catch(Exception e) {
            list = new JList(listModel);
            field = new JTextField();
            getContentPane().add(field, BorderLayout.NORTH);
            getContentPane().add(new JScrollPane(list), BorderLayout.CENTER);
            setSize(400, 300);
            field.addKeyListener(new KeyAdapter() {
                  public void keyReleased(KeyEvent e) {
                        char text = "" + e.getKeyChar();
                        StringBuffer buffer = new StringBuffer();

                        int index = list.getNextMatch(buffer, 0, Position.Bias.Forward);
      public static void main(String[] args) {
            ListSearch h = new ListSearch();

My sample text is:


The problem is when the user tries to type any on the text it only selects the 1st one? Can anyone help
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 2 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 2 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros