JList and JComboBox of Swing

Hello everyone. This page is an English translation of a Japanese page. (The original Japanese has been slightly rewritten to make it easier to translate into English.)

In this article, we have dealt with JList and JComboBox provided in Swing.

JList and JComboBox are components that display a list of items and allow the user to select an item. There are the following differences in the way they are displayed.

JList
All items will be displayed. The selected item will change color.
JComboBox
The selected item will be displayed. Selecting an item is a pull-down type.

We will use the following program as a template.

Source
import javax.swing.JFrame;

public class Test extends JFrame {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(350, 250);

        init();

        setVisible(true);

    }

    private void init() {
        // installation process
    }

}

JList

コンストラクタJList(E[] listData)

The JList class is a class that handles implementation classes for the AbstractListModel<E> interface. The constructor JList(E[] listData) allows you to use the AbstractListModel without being aware of it. As for the processing of JList(E[] listData), internally an anonymous class of AbstractListModel is generated and passed to the constructor JList(ListModel<E> dataModel).

The easiest example to specify for Generics E is the String type. It is important to note that the result of the toString() method will be output for the class specified in the generics.

In the following example, we used an array of type String and an array of type Double.

Source
import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JList;

public class Test2 extends JFrame {

    public static void main(String[] args) {
        new Test2();
    }

    public Test2() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(350, 250);

        init();

        setVisible(true);

    }

    private void init() {
        setLayout(new FlowLayout());

        String[] data1 = { "item01", "item02", "item101", "item102" };
        JList<String> list1 = new JList<>(data1);
        add(list1);

        Double[] data2 = { 0.1, 0.2 };
        JList<Double> list2 = new JList<>(data2);
        add(list2);
    }

}
SwingDay006JList001.png

A list using an array of type Double will display a string with a decimal point. This is because the toString() method of the elements of the list is executed.

As mentioned earlier, the constructor JList(E[] listData) calls the constructor JList(ListModel<E> dataModel). An anonymous class that implements AbstractListModel<E> is generated from the array specified in the argument. Therefore, as shown in Source above, you can program without being aware of the AbstractListModel<E> interface.

Get the selected item.

According to the API specification, there are several methods to get the selected item. In this section, we will introduce the getSelectedValuesList method. The return value of this method is the item selected in List<E>. If nothing is selected, an empty list will be returned.

The following sample will output the selected item to the console when the button is pressed.

Source
import java.awt.FlowLayout;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;

public class Test3 extends JFrame {

    public static void main(String[] args) {
        new Test3();
    }

    public Test3() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(350, 250);

        init();

        setVisible(true);

    }

    private void init() {
        setLayout(new FlowLayout());

        String[] data1 = { "item01", "item02", "item101", "item102" };
        JList<String> list1 = new JList<>(data1);
        add(list1);

        JButton button = new JButton("GET");
        add(button);
        button.addActionListener(event -> {
            List<String> items = list1.getSelectedValuesList();
            for (String s : items) {
                System.out.println(s);
            }
        });
    }

}

In the above program, JList is declared as JList<String>. Therefore, the value returned by the getSelectedValuesList() method is List<String>.

ListSelectionListener

If you have a process that you want to execute when a selection item is changed, you can add a listener with the addListSelectionListener() method. The class specified as the argument of the method is the class that implements the ListSelectionListener interface. In this interface, only valueChanged(ListSelectionEvent e) is defined. This method is called when a value in the selected range of the list is changed.

The following sample will output the selected item to the console whenever the selected item is changed.

Source
import java.awt.FlowLayout;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JList;

public class Test4 extends JFrame {

    public static void main(String[] args) {
        new Test4();
    }

    public Test4() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(350, 250);

        init();

        setVisible(true);

    }

    private void init() {
        setLayout(new FlowLayout());

        String[] data1 = { "item01", "item02", "item101", "item102" };
        JList<String> list1 = new JList<>(data1);
        add(list1);

        list1.addListSelectionListener(event -> {
            List<String> items = list1.getSelectedValuesList();
            for (String s : items) {
                System.out.println(s);
            }
        });
    }
}

We have actually checked the above behavior, but the mouse operation called the method twice for each click. Maybe there is another appropriate way.

JComboBox

Constructor JComboBox(E[] items)

JComboBox also has a constructor whose argument is E[] items, just like JLabel. The following is an example using a String array.

Source
import java.awt.FlowLayout;

import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Test5 extends JFrame {

    public static void main(String[] args) {
        new Test5();
    }

    public Test5() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(350, 250);

        init();

        setVisible(true);

    }

    private void init() {
        setLayout(new FlowLayout());

        String[] data = { "item01", "item02", "item101", "item102" };
        JComboBox<String> comboBox = new JComboBox<>(data);
        add(comboBox);
    }

}

The following is the initial display.

SwingDay006JComboBox001.png

When the JComboBox was clicked, the following was displayed.

This constructor generates the default model of the combo box with new DefaultComboBoxModel<E>(items) and passes it to the setModel() method.

Get the selected item

The int getSelectedIndex() method is implemented as a method to get the selected items. In this method, the integer value for the currently selected list item is returned. The first item corresponds to the integer value 0.

In the following sample, when a button is pressed, the integer corresponding to the selected item is displayed in the console.

Source
import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Test6 extends JFrame {

    public static void main(String[] args) {
        new Test6();
    }

    public Test6() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(350, 250);

        init();

        setVisible(true);

    }

    private void init() {
        setLayout(new FlowLayout());

        String[] data = { "item01", "item02", "item101", "item102" };
        JComboBox<String> comboBox = new JComboBox<>(data);
        add(comboBox);

        JButton button = new JButton("GET");
        add(button);
        button.addActionListener(event -> {
            int index = comboBox.getSelectedIndex();
            System.out.println(index);
        });
    }

}

When the item with the label “item01" is selected, the integer value 0 will be displayed, and when the item with the label “item02" is selected, the integer value 1 will be displayed.

ActionListener

JComboBox provides the addActionListener() method.
By specifying the ActionListener implementation class as an argument, the process to be executed when an item is selected can be described.

In the following example, when an item is selected, “Selected." will be displayed in the console.

Source
import java.awt.FlowLayout;

import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Test7 extends JFrame {

    public static void main(String[] args) {
        new Test7();
    }

    public Test7() {
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize(350, 250);

        init();

        setVisible(true);

    }

    private void init() {
        setLayout(new FlowLayout());

        String[] data = { "item01", "item02", "item101", "item102" };
        JComboBox<String> comboBox = new JComboBox<>(data);
        add(comboBox);

        comboBox.addActionListener(event -> {
            System.out.println("Selected.");
        });
    }

}

You can also select items by using the up/down arrow keys instead of clicking. In this case, “Selected." will also be output.

That’s all. I hope this is helpful to you.

Articles next and previous in the same category