maximus
maximus

Reputation: 4302

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

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.

Upvotes: 5

Views: 14127

Answers (3)

trashgod
trashgod

Reputation: 205785

JComboBox is a common choice for this. AutoCompleteJComboBoxer is one I've tried.

Upvotes: 3

Heisenbug
Heisenbug

Reputation: 39164

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.

Upvotes: 4

Abhishek Choudhary
Abhishek Choudhary

Reputation: 8385

Well .... in the JTextField , add a listener for keypress and then as soon as any key is getting pressed , use a set to sort all the related elements. An option is having the String to toChar for getting each character and then post the records in the JList.

Secondly , you better keep your records in an XML then tracking will be easier rest any kind of sorting algorithm logic can be easily applied.

Upvotes: 1

Related Questions