Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 638
maximus Avatar asked Jun 25 '11 15:06

maximus


3 Answers

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.

like image 185
Heisenbug Avatar answered Nov 19 '22 21:11

Heisenbug


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

like image 3
trashgod Avatar answered Nov 19 '22 21:11

trashgod


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.

like image 1
Abhishek Choudhary Avatar answered Nov 19 '22 23:11

Abhishek Choudhary