How to make a text field for searching(with tips like a google search)

maximus picture maximus · Jun 25, 2011 · Viewed 11.8k times · Source

I want to make a window application for PC using java swing. I would like to make a text field there. While typing to that text field I need it to show tips under that text field. And user can select the needed text from the list. The same like the google searching does in the browser. So I need some two functions, first one is easy: filter a set of strings by already typed text. But how to show them in a list ?

EDIT1: I need the list to be shown if there is something to show after filtration, and an ability to select by using keys up and down. The same as google search but on PC application.

Answer

Heisenbug picture Heisenbug · Jun 25, 2011

I suggest you to add a DocumentChangeListener to your JTextField to monitor the inserted/deleted/update chars:

JTextField textField = new JTextField;
textField.addDocumentListener (new DocumentListener() {
  public void changedUpdate(DocumentEvent e) {
  }
  public void removeUpdate(DocumentEvent e) {
  }
  public void insertUpdate(DocumentEvent e) {
  }
}
);

Have a look of this tutorial.

So I need some two functions, first one is easy: filter a set of strings by already typed text.

Now that you have the typed text, filter your set of strings. Be careful in choosing an efficient way to store and retrieve strings from your data structure. With a lot of string to sort this may not be trivial. (I think it will be hard to this with an ArrayList if you set of strings if quite big.)

But how to show them in a list ?

I think you could use a JLabel. Alternatively you can try with a JComboBox implementing your own ComboBoxModel. I don't know if it is possible to keep always open the combo box.