Filtering JList Component Models

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

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.

How do I get the items of a JList components?

In this example you can see how we can read the items of a JList component. We also obtain the size or the number of items in the JList components.

This can be done by calling JList‘s getModel() method which return a ListModel object. From the ListModel we can get the items size, and we can iterate the entire items of the JList component.

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;
import java.text.DateFormatSymbols;

public class JListGetItems extends JFrame {
    public JListGetItems() {
        initialize();
    }

    public static void main(String[] args) {
        // Run the program, create a new instance of JListGetItems and
        // set its visibility to true.
        SwingUtilities.invokeLater(
                () -> new JListGetItems().setVisible(true));
    }

    private void initialize() {
        // Configure the frame default close operation, its size and the
        // layout.
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setSize(500, 500);
        this.setLayout(new BorderLayout(5, 5));

        // Create a JList and set the items to the available weekdays
        // names.
        Object[] listItems = DateFormatSymbols.getInstance().getWeekdays();
        JList<Object> list = new JList<>(listItems);
        getContentPane().add(list, BorderLayout.CENTER);

        // Below we start to print the size of the list items and iterates
        // the entire list items or elements.
        System.out.println("JList item size: " + list.getModel().getSize());

        System.out.println("Reading all JList items:");
        System.out.println("-----------------------");
        for (int i = 0; i < list.getModel().getSize(); i++) {
            Object item = list.getModel().getElementAt(i);
            System.out.println("Item = " + item);
        }
    }
}

And here is the result:

JList item size: 8
Reading all JList items:
-----------------------
Item = 
Item = Sunday
Item = Monday
Item = Tuesday
Item = Wednesday
Item = Thursday
Item = Friday
Item = Saturday

How do I set the cell width and height of a JList component?

The cell width and height of a JList can be defined by setting the fixedCellWidth and fixedCellHeight properties. These properties have a corresponding methods called setFixedCellWidth(int width) and setFixedCellHeight(int height).

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;
import java.util.Vector;

public class JListCellWidthAndHeight extends JFrame {
    public JListCellWidthAndHeight() {
        initialize();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new JListCellWidthAndHeight().setVisible(true));
    }

    private void initialize() {
        // Initialize windows default close operation, size and the layout
        // for laying the components.
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setSize(500, 175);
        setLayout(new BorderLayout(5, 5));

        // Create a list of vector data to be used by the JList component.
        Vector<String> v = new Vector<>();
        v.add("A");
        v.add("B");
        v.add("C");
        v.add("D");

        JList<String> list = new JList<>(v);
        list.setFixedCellWidth(50);
        list.setFixedCellHeight(50);

        JScrollPane pane = new JScrollPane(list);

        // Add an action listener to the button to exit the application.
        JButton button = new JButton("CLOSE");
        button.addActionListener(e -> System.exit(0));

        // Add the scroll pane where the JList component is wrapped and
        // the button to the center and south of the panel
        getContentPane().add(pane, BorderLayout.CENTER);
        getContentPane().add(button, BorderLayout.SOUTH);
    }
}
JList Cell Width and Height Demo

JList Cell Width and Height Demo

How do I create a JList component?

JList is a component that displays a list of objects and allow user to select one or more items. To create an instance of JList we can pass a vector, an array of objects or a ListModel. In this example we will pass an array of objects that contains a date, string and numbers as the parameters.

By default, the list does not display a scrollbar. To give our JList component a scrollbar we must wrap it with a JScrollPane.

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;
import java.util.Date;

public class CreateJListDemo extends JFrame {

    public CreateJListDemo() {
        initialize();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(
                () -> new CreateJListDemo().setVisible(true));
    }

    // Initialize the components and configuration of our CreateJListDemo.
    private void initialize() {
        // Define the window title, size and the default close operation.
        this.setTitle("Create JList Demo");
        this.setSize(500, 175);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        // Create an array of arbitrary objects for the JList to display.
        Object[] data = new Object[]{
                new Date(), "One", 1, Long.valueOf("12345"), "Four", "Five"
        };

        // Create an instance of JList and pass data variable as the
        // initial content of it. By default, the JList does not have a
        // scrolling behaviour, so we create a JScrollPane as the container
        // for the JList.
        JList<Object> list = new JList<>(data);
        JScrollPane scrollPane = new JScrollPane(list);

        // Add a button to close the program.
        JButton button = new JButton("Close");
        button.addActionListener(e -> System.exit(0));

        // Set the panel layout to BorderLayout and place the list in the
        // center and the button on the south.
        this.setLayout(new BorderLayout(5, 5));
        getContentPane().add(scrollPane, BorderLayout.CENTER);
        getContentPane().add(button, BorderLayout.SOUTH);
    }
}
Swing JList Demo

Swing JList Demo