Filter items in a long list are often accomplished using the JTextField
component. As the user inputs into the JTextField
component, the set of items shown in the list is narrowed to just those things that correspond to the input received from the user.
It is necessary to utilize two elements to implement this function of the JList
component, one of which is a model that filters a set of elements based on some text. The other executes the filter method when the user enters text.
Implementing the input field is a simpler job, so let’s start with it in our review of the implementation process. The JTextField
component model is a document used with a Swing set of components. It is necessary to implement the DocumentListener
interface in the model in order to monitor input to a Document. Text input, updating, and deletion are tracked using three methods defined below:
public void insertUpdate (DocumentEvent event)
public void changedUpdate (DocumentEvent event)
public void removeUpdate (DocumentEvent event)
When the model attributes are updated, the changedUpdate()
method is used to update the model. It is possible that it will not be realized. In order to avoid duplicating filtering actions across all three methods, the generic method generated in the custom model is simply called by the other two. A detailed explanation of the JTextField
component, which is used for filtering in the JList
component, may be found in the following section:
JTextField input = new JTextField();
String lastSearch = "";
DocumentListener listener = new DocumentListener() {
public void insertUpdate(DocumentEvent event) {
Document doc = event.getDocument();
lastSearch = doc.getText(0, doc.getLength());
((FilteringModel)getModel()).filter(lastSearch);
}
public void removeUpdate(DocumentEvent event) {
Document doc = event.getDocument();
lastSearch = doc.getText(0, doc.getLength());
((FilteringModel)getModel()).filter(lastSearch);
}
public void changedUpdate(DocumentEvent event) {
}
};
input.getDocument().addDocumentListener(listener);
In order to avoid being restricted to just using the JTextField
component that was generated using the JList
, the installJTextField()
method is used, which attaches the event listener to the component that was built using the JList
in the first place. In addition, a mechanism is provided to eliminate this match. Through the usage of these methods, the user of a filtering JList
may choose to use their own JTextField
in place of the default one.
public void installJTextField(JTextField input) {
input.getDocument().addDocumentListener(listener);
}
public void unnstallJTextField(JTextField input) {
input.getDocument().removeDocumentListener(listener);
}
After that, the filtering model is taken into consideration. This case implements the filter()
function, which is invoked by methods that implement the DocumentListener
interface, as seen below. To put this strategy into action, you’ll need to have two lists of objects on hand: a source list and a filtered list of items. Because you are inheriting from the AbstractListModel
class, you must implement some of the methods listed below in your code:
- Constructor
- Method for adding items to the model is being implemented in this project.
getElementAt()
is used to get an element.
getSize()
is used to retrieve sizes.
-
The constructor produces two instances of the List objects. The type of objects that are stored as List elements does not matter. Therefore List objects are generated to carry items of the following types:
List<Object> list;
List<Object> filteredList;
public FilteringModel() {
list = new ArrayList<>();
filteredList = new ArrayList<>();
}
Model elements are added by adding them to the original model and then filtering the resulting model with the previously added elements. Optimization of this approach may be achieved by using a method to filter a single element when it is added; however, in this implementation, the filter()
function is invoked when an element is added, which is also used to filter the whole list. (It should be noted that the event implementation in the DocumentListener
also invokes the filter()
method.) As a result, even when only one item is added to the list, the whole list is filtered, with each item that matches the search parameters being added to the filtered list.
public void addElement(Object element) {
list.add(element);
filter();
}
The size of the returned model is the same as the size of the filtered list, but not the same as the original:
public int getSize() {
return filteredList.size();
}
Similar to the technique for obtaining the size of a model, the method for obtaining an item from a list returns elements from the filtered list rather than the original list. In order to avoid having to go through the complete list, it has been implemented as follows:
public Object getElementAt(int index) {
Object returnValue;
if (index < filteredList.size()) {
returnValue = filteredList.get(index);
} else {
returnValue = null;
}
return returnValue;
}
Finally, the filter()
method is responsible for most of the work. Because you have no way of knowing whether the new search string will broaden or limit the set of items, the quickest and most straightforward solution is to remove the whole filtered list and replace it with items that fit your search criteria from the original list. A match may be discovered at the beginning of a line as well as at any point throughout it. An example of searching for the letter “A” is shown below. This function enables you to locate items in a string that begin with the capital letter “A” or contain the letter “A” at any point in the string.
void filter(String search) {
filteredList.clear();
for (Object element: list) {
if (element.toString().contains(search)) {
filteredList.add(element);
}
}
fireContentsChanged(this, 0, getSize());
}
It is important to note that the search in this approach is case-sensitive. You may alter the method to implement a case-insensitive search and start the search at the beginning of the string.
After you have added entries to the filtered list, you may also sort the results. This operation requires your familiarity with the model’s contents. The function toString()
is currently used by search, which does not indicate that it may include elements of a suitable type that can also be sorted when it is performed.
Here is a full implementation of the JList
filter element with an inner class ListModel
, as seen in the accompanying code sample. This class implements the DocumentListener
interface, which the text component uses to listen for new documents. Although the addition of this class may seem needless at first look, given that filtering is only done for this model, the specification of behavior in this implementation is the most accurate.
package org.kodejava.swing;
import javax.swing.AbstractListModel;
import javax.swing.JList;
import javax.swing.JTextField;
import javax.swing.ListModel;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import java.util.ArrayList;
import java.util.List;
public class FilteringJList extends JList<Object> {
private JTextField input;
public FilteringJList() {
setModel(new FilteringModel());
}
public void installJTextField(JTextField input) {
if (input != null) {
this.input = input;
FilteringModel model = (FilteringModel) getModel();
input.getDocument().addDocumentListener(model);
}
}
public void uninstallJTextField(JTextField input) {
if (input != null) {
FilteringModel model = (FilteringModel) getModel();
input.getDocument().removeDocumentListener(model);
this.input = null;
}
}
public void setModel(ListModel<Object> model) {
if (!(model instanceof FilteringModel)) {
throw new IllegalArgumentException();
} else {
super.setModel(model);
}
}
public void addElement(Object element) {
((FilteringModel) getModel()).addElement(element);
}
private static class FilteringModel extends AbstractListModel<Object> implements DocumentListener {
List<Object> list;
List<Object> filteredList;
String lastFilter = "";
public FilteringModel() {
list = new ArrayList<>();
filteredList = new ArrayList<>();
}
public void addElement(Object element) {
list.add(element);
filter(lastFilter);
}
public int getSize() {
return filteredList.size();
}
public Object getElementAt(int index) {
Object returnValue;
if (index < filteredList.size()) {
returnValue = filteredList.get(index);
} else {
returnValue = null;
}
return returnValue;
}
void filter(String search) {
filteredList.clear();
for (Object element : list) {
if (element.toString().contains(search)) {
filteredList.add(element);
}
}
fireContentsChanged(this, 0, getSize());
}
public void insertUpdate(DocumentEvent event) {
Document doc = event.getDocument();
try {
lastFilter = doc.getText(0, doc.getLength());
filter(lastFilter);
} catch (BadLocationException ble) {
System.err.println("Bad location: " + ble);
}
}
public void removeUpdate(DocumentEvent event) {
Document doc = event.getDocument();
try {
lastFilter = doc.getText(0, doc.getLength());
filter(lastFilter);
} catch (BadLocationException ble) {
System.err.println("Bad location: " + ble);
}
}
public void changedUpdate(DocumentEvent event) {
}
}
}
It is now necessary to develop a test program. The following six lines will be crucial in the event. They build a JList
component, attach it to the JScrollPane
component, and then attach a text box to it as seen in the code:
FilteringJList list = new FilteringJList();
JScrollPane pane=new JScrollPane(list);
frame.add(pane,BorderLayout.CENTER);
JTextField text=new JTextField();list.installJTextField(text);
frame.add(text,BorderLayout.NORTH);
To the model, new components are introduced in the program’s primary body. The model shown below includes a list of Christmas gifts, the names of Santa’s reindeer, the names of London Underground lines, and the letters of the Greek alphabet.
package org.kodejava.swing;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.EventQueue;
public class JListFiltersDemo {
public static void main(String[] args) {
Runnable runner = () -> {
JFrame frame = new JFrame("Filtering List");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FilteringJList list = new FilteringJList();
JScrollPane pane = new JScrollPane(list);
frame.add(pane, BorderLayout.CENTER);
JTextField text = new JTextField();
list.installJTextField(text);
frame.add(text, BorderLayout.NORTH);
String[] elements = {
"Partridge in a pear tree", "Turtle Doves", "French Hens",
"Calling Birds", "Golden Rings", "Geese-a-laying",
"Swans-a-swimming", "Maids-a-milking", "Ladies dancing",
"Lords-a-leaping", "Pipers piping", "Drummers drumming",
"Dasher", "Dancer", "Prancer", "Vixen", "Comet", "Cupid",
"Donner", "Blitzen", "Rudolf", "Bakerloo", "Center",
"Circle", "District", "East London", "Hammersmith and City",
"Jubilee", "Metropolitan", "Northern", "Piccadilly Royal",
"Victoria", "Waterloo and City", "Alpha", "Beta", "Gamma",
"Delta", "Epsilon", "Zeta", "Eta", "Theta", "Iota", "Kappa",
"Lambda", "Mu", "Nu", "Xi", "Omicron", "Pi", "Rho", "Sigma",
"Tau", "Upsilon", "Phi", "Chi", "Psi", "Omega"};
for (String element : elements) {
list.addElement(element);
}
frame.setSize(500, 500);
frame.setVisible(true);
};
EventQueue.invokeLater(runner);
}
}
Filtering JList Component Models Demo
Because this filtering strategy is based on the JList
component and its accompanying JTextField
component, it will operate successfully if your list’s entries are appropriately displayed when you use the function toString()
. Creating a Filter interface that is provided to the model when filtering operations are performed might be useful for doing more complicated filtering tasks.
In this example, the only item that is not addressed is the process of selection. By default, when the contents of the model list change, the JList
does not update the selection of the model list. Filtering may be used to either retain the chosen item or emphasize the first item in the list, depending on the desired behavior.
Even though the original JList
component does not explicitly offer the functionality, there are techniques to implement filtering. Overriding the getNextMatch()
function allows you to alter the default behavior if you so want.