In this tutorial

You will learn how to...
  • How to create a JList.
  • How to select different amounts in the JList.
  • How to add items to a JList.
  • How to remove items from a JList.

JList - Part 1

The JList is a way of displaying a selectable list on the screen.

The JList uses a special event listener, designed specifically for a list. It's called a ListSelectionListener and we use it in this example.

In this example, we go back to our boxes. A box is only shown when it is selected on the list, and the list is constrained to only one selection at a time. Later in the tutorial we will show you how to deal with multiple selections, but lets try and understand this code first.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.Color;
import java.awt.event.*;

public class ListExample implements  ListSelectionListener{

    JList boxes;
    JPanel[] boxArray = new JPanel[10];
    
    public JPanel createContentPane (){
        
        JPanel totalGUI = new JPanel();
        
        // Array for the names to be in the list.
        String names[] = {"Red", "Blue", "Green", "Orange", "Yellow",
                          "Pink", "Cyan", "Gray", "Black", "Magenta"};
        
        // Creation of the list.
        // We set the cells in the list to be 20px x 140px.
        // And set the 'selection mode' to single, so only one thing
        // can be selected at any time.
        // We finish by adding an event listener for the List.
        
        boxes = new JList(names);
        boxes.setVisibleRowCount(10);
        boxes.setFixedCellHeight(20);
        boxes.setFixedCellWidth(140);
        boxes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        boxes.addListSelectionListener(this);
        
        // We create a JPanel with the GridLayout.
        JPanel mainPanel = new JPanel(new GridLayout(3, 4, 10, 30));

        boxArray[0] = createSquareJPanel(Color.red, 50);
        boxArray[1] = createSquareJPanel(Color.blue, 50);
        boxArray[2] = createSquareJPanel(Color.green, 50);
        boxArray[3] = createSquareJPanel(Color.orange, 50);
        boxArray[4] = createSquareJPanel(Color.yellow, 50);
        boxArray[5] = createSquareJPanel(Color.pink, 50);
        boxArray[6] = createSquareJPanel(Color.cyan, 50);
        boxArray[7] = createSquareJPanel(Color.gray, 50);
        boxArray[8] = createSquareJPanel(Color.black, 50);
        boxArray[9] = createSquareJPanel(Color.magenta, 50);
        
        // This sets every JPanel in the array to be hidden,
        // and then adds it to the mainPanel JPanel.
        
        for(int i = 0; i < 10; i++)
        {
            boxArray[i].setVisible(false);
            mainPanel.add(boxArray[i]);
        }
        
        // This final bit of code uses a BoxLayout to space out the widgets
        // in the GUI.
        
        JPanel bottomPanel = new JPanel();
        bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));
        
        bottomPanel.add(Box.createRigidArea(new Dimension(10,0)));
        bottomPanel.add(boxes);
        bottomPanel.add(Box.createRigidArea(new Dimension(10,0)));
        bottomPanel.add(mainPanel);
        bottomPanel.add(Box.createRigidArea(new Dimension(10,0)));
        
        totalGUI.add(bottomPanel);
        totalGUI.setOpaque(true);
        return totalGUI;
    }

    // In this method, we create a square JPanel of a colour and set size
    // specified by the arguments.

    private JPanel createSquareJPanel(Color color, int size) {
        JPanel tempPanel = new JPanel();
        tempPanel.setBackground(color);
        tempPanel.setMinimumSize(new Dimension(size, size));
        tempPanel.setMaximumSize(new Dimension(size, size));
        tempPanel.setPreferredSize(new Dimension(size, size));
        return tempPanel;
    }

    // valueChanged is the method that deals with a ListSelectionEvent.
    // This one sets the Visibility of the chosen box to true, and the
    // rest to false.

    public void valueChanged(ListSelectionEvent e) {

        if (e.getValueIsAdjusting() == false) {
            if (e.getSource() == boxes) {
                for(int i = 0; i < 10; i++)
                {
                    if (i == boxes.getSelectedIndex())
                    {
                         boxArray[i].setVisible(true);
                    }
                    else
                    {
                         boxArray[i].setVisible(false);
                    }
                } 
            }
        }
    }

    private static void createAndShowGUI() {
    
        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("[=] JListExample [=]");

        ListExample demo = new ListExample();
        frame.setContentPane(demo.createContentPane());
        
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
GUI Picture

The creation of a list here is quite large, but there is nothing tricky.
We create an array of Strings to be put in the list, and then instantiate the JList with the array as an argument.
17
18
        String names[] = {"Red", "Blue", "Green", "Orange", "Yellow",
                          "Pink", "Cyan", "Gray", "Black", "Magenta"};
26
        boxes = new JList(names);
The JList is then sized by using setVisibleRowCount() to tell the LayoutManager the number of rows that should be visible. Then we use setFixedCellWidth() and setFixedCellHeight() to set the size of a cell within the List (in this case 140px by 20px).
27
28
29
        boxes.setVisibleRowCount(10);
        boxes.setFixedCellHeight(20);
        boxes.setFixedCellWidth(140);
We set the Selection Mode to be singular so that only one item can be selected at any time on the list, then finally put in a ListSelectionListener to track any changes in the list.
30
31
        boxes.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        boxes.addListSelectionListener(this);
Dealing with the selection of a cell in a List is not too difficult, you just need to know the syntax. We start down in the valueChanged() method by checking to make sure the user is finished selecting cells. This isn't really very useful to us right now as we can only select one cell at a time, but in the next example it will be of use.
90
91
        if (e.getValueIsAdjusting() == false) {
Once we are happy with that, we change the visibility of the boxes to match what is selected on the list by using getSelectedIndex(). No problem.
93
94
95
96
97
98
99
100
101
102
103
                for(int i = 0; i < 10; i++)
                {
                    if (i == boxes.getSelectedIndex())
                    {
                         boxArray[i].setVisible(true);
                    }
                    else
                    {
                         boxArray[i].setVisible(false);
                    }
                } 
Simple enough. Let's move on now to looking at how to select more than one item from the list.

Back Top Next
Email Me
Code Style


Required Lessons

External Links

Created and Edited by Stuart Davidson
All Rights Reserved ©

Valid XHTML 1.0 Strict