0

I have 1 column with 100 names, all from A to Z. I have to choose 1. I want to be able to insert a few letters into a jtextfield, press enter, and have the row be selected that matches the text. How do I do this?

An example would be, I type "Bro", press enter and the selection skips to the first name that starts with "Bro". I dont mean a filter, I want to skip to it.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

1 Answers1

1

I have 1 column

So why are you using a JTable? Why not use a JList?

I want to be able to insert a few letters into a jtextfield, press enter,

You can do the search as every letter is typed (or removed), instead of forcing the user to press Enter.

  1. Create a JTextField for entering the name to search for:
  2. Add a DocumentListener to the Document of the text field. Read the section from the Swing tutorial on Listening For Changes on a Document for the basics.
  3. In the DocumentListener you would get the model of your JList (or JTable) and then iterate through each item in the model to find the index of the first item that starts with the text in the text field.
  4. If you use a JList then you just use the setSelectedIndex(...) methodto select the row and the ensureIndexIsVisible(...) method to scroll to the row
  5. if you use a JTable then you use the changeSelection(...) method to select the row and then the scrollRectToVisible(...) method to scroll to the row using data from the getCellRect(...) method.
camickr
  • 321,443
  • 19
  • 166
  • 288