JList component with filtering function [Swing]

Source: Internet
Author: User

Scenario: You can enter a character in a list to dynamically filter the display of items in the list. Of course, all the items displayed dynamically contain characters entered by the user! Here, the implementation of the function is very simple, there is no more
Complex logic. It only provides some examples for learners. You can perform the extensions you need.
[Relationship diagram ]:


In Swing, to build your own components, the simplest thing is to inherit the existing components, and then perform customizable function extensions without doing too much extra work, swing provides us with good performance.
Scalability ., A brief description of the List relation class chart to be developed that can be filtered. Here are some simple descriptions:
[FilteredList]: inherits JList. The class FilteredModel and FilteredTextField are their internal class implementations. Use it here
Internal classes are used to facilitate access to the external data of FilteredList and reduce interaction with external classes. It cannot be determined whether this method is good or bad, the measurement is left to the user.
[FilteredModel]: inherits the internal classes in AbstractListModel and FilteredList and exists as an attribute of them. The function is to save
Displays data in the list and can be dynamically updated.
[FilteredTextField]: inherits JTextFiled. Obviously, it is an input box that only implements a DocumentListener interface,
Monitors any user input actions in real time: insert, delete, modify, and so on. When you trigger this listener, you need to interact with the FilteredModel to dynamically change
Display Data in FilteredList.

[Coding implementation]
FilteredModel
:
In this Model, we mainly set a filteredItems
Attribute, which is used to save the list items that contain user input characters. Another items attribute stores all the original items in the list. The key algorithm is method refilter (): real-time processing of user input.
Filter and add the results to filtereditems.
Private class filtermodel extends actlistmodel {
Private list items;
Private list filtereditems;
Public filtermodel (){
Items = new arraylist ();
Filtereditems = new arraylist ();
}

Public void addelement (Object O) {// Add an item to the list
Items. Add (O );
Refilter (); // update filteritems every time an item is added
}

Private void Refilter (){
Filtereditems. Clear ();
String item = getfilterfield (). gettext ();
For (INT I = 0; I <items. Size (); I ++ ){
If (items. Get (I). tostring (). touppercase (). indexof (item, 0 )! =-1
| Items. Get (I). tostring (). tolowercase (). indexof (item,
0 )! =-1 ){
Filtereditems. Add (items. Get (I ));
}
}
Firecontentschanged (this, 0, filtereditems. Size ());
}

@ Override
Public object getelementat (INT index ){
If (index <filtereditems. Size ()){
Return filtereditems. Get (INDEX );
}
Return NULL;
}

@ Override
Public int getsize (){
Return filtereditems. Size ();
}
}

[Filterfield]
Private class filterfield extends jtextfield implements documentlistener
{
Public filterfield (INT width ){
Super (width );
Getdocument (). adddocumentlistener (this );
}

@ Override
Public void changedupdate (documentevent e ){
Model. Refilter (); // update the display data of the list, the same below
}

@ Override
Public void insertupdate (documentevent e ){
Model. Refilter ();
}

@ Override
Public void removeupdate (documentevent e ){
Model. Refilter ();
}
}

[Filteredlist]
Public class filteredlist extends jlist {
Private filtermodel model;

Private filterfield;

Public filteredlist (){
Model = new filtermodel ();
Setmodel (model );
Filterfield = new filterfield (20 );
}

Public void additem (Object O ){
Model. addelement (O );
}

Public filterfield getfilterfield (){
Return filterfield;
}
}
Visible,FilteredList
The implementation is very simple. You only need to define the component that has been created as its property. And change the model.
Use a self-implemented model with the filtering function.
The following is a test code:
Public static void main (String [] args ){
String [] listItems = {"Chris", "Joshua", "Daniel", "Michael", "Don ",
"Kimi", "Kelly", "Keagan "};
JFrame frame = new JFrame ("FilteredJList ");
Frame. getContentPane (). setLayout (new BorderLayout ());
// Populate list
FilteredHistoryList list = new FilteredHistoryList ();
For (int I = 0; I <listItems. length; I ++)
List. addItem (listItems [I]);
// Add to gui
JScrollPane pane = new JScrollPane (list,
ScrollPaneConstants. VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants. HORIZONTAL_SCROLLBAR_NEVER );
Frame. getContentPane (). add (pane, BorderLayout. CENTER );
Frame. getContentPane (). add (list. getFilterField (), BorderLayout. NORTH );
Frame. pack ();
Frame. setVisible (true );
Frame. setdefaclocloseoperation (JFrame. EXIT_ON_CLOSE );
}

[Summary]
Here, we only add a specific layer of functionality to a JList. Of course, we can't just learn how to compile the code for this function, but also understand how to implement it internally, why?
Do this.
Here, the Inheritance Mechanism and interface implementation all use sophisticated component classes of the class library, so that many features can be reused. What we need is to add an additional feature to JList, so of course we need to inherit from
JList, so that they have kinship, convenient management! Here we can also feel the feeling of Swing encoding: the data and presentation layer are clearly divided, and the presentation and data are not coupled. Of course,
It can be said that in this example, we have not done a good job or made a specific level of optimization. You can try it on your own ......

[Reference ]:《Swing Hacks
By Chris Adamson
,
Joshua Marinacci

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.