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

雨燕双飞 提交于 2019-12-23 10:55:10

问题


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.


回答1:


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




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/6478577/how-to-make-a-text-field-for-searchingwith-tips-like-a-google-search

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!