Header javaperspective.com

5.21. Lists
Last updated: 25 January 2013.

This tutorial will show you how to use lists in Java.

A list is an instance of the class JList. It is a component that exposes items that can be selected in 3 different modes:A list can be displayed in a single column or in multiple columns. As an example, the following picture shows a frame containing a single-column list (with single selection mode) that exposes languages starting with the letter A:


Lists


Here is the code:

import java.awt.Dimension;

import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public final class Lists extends JFrame {

   
public Lists() {
         
init();
          addComponents
();

          setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
          setVisible
(true);
   
}


   
private void addComponents() {
         
// Create the content pane
         
JPanel contentPane = new JPanel();

         
// Create the array of objects containing the list items
         
Object[] listItems = {
                     
"Abkhazian", "Afrikaans", "Albanian", "Amharic", "Arabic", "Aragonese",
                     
"Armenian", "Assamese", "Asturian", "Aymara", "Azerbaijani"
         
};

         
// Create the list
         
JList<Object> list = new JList<Object>(listItems);
          list.setSelectionMode
(ListSelectionModel.SINGLE_SELECTION);

         
// Wrap a scroll pane around the list
         
JScrollPane scrollPane = new JScrollPane(list);
          scrollPane.setPreferredSize
(new Dimension(100, 150));

         
// Add the scroll pane to the content pane
         
contentPane.add(scrollPane);

         
// Add the content pane to the JFrame
         
add(contentPane);
   
}


   
private void init() {
         
try{
               
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
         
}
         
catch(Exception e){
               
e.printStackTrace();
         
}

         
setTitle("Lists");
          setSize
(200, 200);
          setLocationRelativeTo
(null);
   
}


   
public static void main(String[] args){
         
SwingUtilities.invokeLater(new Runnable() {
               
public void run() {
                     
new Lists();
               
}
          })
;
   
}
}

The code above is quite minimalistic. Therefore, all the properties of the list are left to their default values except the selection mode which is set by the call to the method setSelectionMode. The possible values are ListSelectionModel.SINGLE_SELECTION, ListSelectionModel.SINGLE_INTERVAL_SELECTION and ListSelectionModel.MULTIPLE_INTERVAL_SELECTION (the default).

Usually, lists are in a single column as in the above example. However, you can set another layout orientation by invoking the method setLayoutOrientation. The possible values are JList.VERTICAL (the default), JList.HORIZONTAL_WRAP and JList.VERTICAL_WRAP. The value HORIZONTAL_WRAP places the list's items in rows, adding new rows as necessary whereas VERTICAL_WRAP places the items in columns, adding new columns as necessary.

The list that I created in the above example is immutable. You cannot add or remove elements from the list after it is created. Furthermore, the events fired by the list are not handled. The next sections will show you how to add/remove items from a list and also how to handle events.


How to add and remove items from a list

To be able to add or remove items from a list, you must provide an instance of the class DefaultListModel and pass it to the constructor of the class JList like this:

// Create the list model
DefaultListModel listModel = new DefaultListModel();

// Add items to the list model
listModel.addElement("Abkhazian");
listModel.addElement
("Afrikaans");
listModel.addElement
("Albanian");
listModel.addElement
("Amharic");
listModel.addElement
("Arabic");

// Create the list
JList list = new JList(listModel);

Next, to remove items, you can use one of the methods provided by the class DefaultListModel: remove(int index), removeAllElements, removeElement(Object obj), removeElementAt(int index) or removeRange(int fromIndex, int toIndex).

To add items to the list, use add(int index, Object element), addElement(Object obj) or set(int index, Object element).


How to handle events fired by a list

List selection events are fired by a list when the selection changes. If you want to listen to those events, you can register a list selection listener on the list by calling the method addListSelectionListener(ListSelectionListener listener). For example, the sample shown below registers a listener which simply prints the selected item of a list to the standard output:

list.addListSelectionListener(new ListSelectionListener() {
   
public void valueChanged(ListSelectionEvent e) {
         
if(e.getValueIsAdjusting() == false)
               
System.out.println(list.getSelectedValue());
   
}
})
;

You might have noticed the call to the method getValueIsAdjusting provided by the class ListSelectionEvent. It simply returns false if the user has finished interacting with the list and true otherwise.

The method getSelectedValue returns the first selected value if the list allows multiple selection. If the list does not allow multiple selection, getSelectedValue returns the selected value. The class JList also provides a method named getSelectedIndex which returns the smallest selected index.

If you are working with a list that allows multiple items selection, you can use the method getSelectedIndices or getSelectedValues to get the array of selected indices or the array of selected values, depending on your needs.


Example of items being transfered between two lists

This section will show you a practical example of two lists placed in a frame like this: there is a list on the left hand side and another one on the right hand side. Between the lists, two buttons allow the user to move items from one list to another. Here is what it looks like:


Lists 2


The code follows:

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public final class Lists2 extends JFrame implements ActionListener, ListSelectionListener {

   
private DefaultListModel<Object> leftListModel;
   
private DefaultListModel<Object> rightListModel;

   
private JList<Object> leftList;
   
private JList<Object> rightList;

   
private JScrollPane leftScrollPane;
   
private JScrollPane rightScrollPane;

   
private JButton moveLeftButton;
   
private JButton moveRightButton;
   
private JPanel buttonsPanel;

   
public Lists2() {
         
init();
          addComponents
();

          setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
          setVisible
(true);
   
}


   
public void actionPerformed(ActionEvent e){
         
if(e.getSource().equals(moveLeftButton)){
               
List<Object> selectedItems = rightList.getSelectedValuesList();
               
for(Object item : selectedItems){
                     
rightListModel.removeElement(item);
                      leftListModel.addElement
(item);
               
}
          }
         
else{
               
List<Object> selectedItems = leftList.getSelectedValuesList();
               
for(Object item : selectedItems){
                     
leftListModel.removeElement(item);
                      rightListModel.addElement
(item);
               
}
          }

         
if(leftListModel.getSize() == 0)
               
moveRightButton.setEnabled(false);
         
else
               
moveRightButton.setEnabled(true);

         
if(rightListModel.getSize() == 0)
               
moveLeftButton.setEnabled(false);
         
else
               
moveLeftButton.setEnabled(true);
   
}


   
private void addComponents() {
         
// Create the content pane
         
JPanel contentPane = new JPanel(new GridBagLayout());

          createLists
();
          createButtons
();

         
// Add the left list to the content pane
         
GridBagConstraints leftListConstraints = new GridBagConstraints();
          leftListConstraints.gridx =
0;
          leftListConstraints.gridy =
0;
          contentPane.add
(leftScrollPane, leftListConstraints);

         
// Add the buttons to the content pane
         
GridBagConstraints buttonsConstraints = new GridBagConstraints();
          buttonsConstraints.gridx =
1;
          buttonsConstraints.gridy =
0;
          contentPane.add
(buttonsPanel, buttonsConstraints);

         
// Add the right list to the content pane
         
GridBagConstraints rightListConstraints = new GridBagConstraints();
          rightListConstraints.gridx =
2;
          rightListConstraints.gridy =
0;
          contentPane.add
(rightScrollPane, rightListConstraints);

         
// Add the content pane to the JFrame
         
add(contentPane);
   
}


   
private void createButtons(){
         
buttonsPanel = new JPanel();
          buttonsPanel.setLayout
(new BoxLayout(buttonsPanel, BoxLayout.PAGE_AXIS));

          moveLeftButton =
new JButton("<<");
          moveRightButton =
new JButton(">>");

          moveLeftButton.setEnabled
(false);
          moveRightButton.setEnabled
(false);

          moveLeftButton.addActionListener
(this);
          moveRightButton.addActionListener
(this);

          buttonsPanel.add
(moveLeftButton);
          buttonsPanel.add
(moveRightButton);
   
}


   
private void createLists(){
         
// Create the list models
         
leftListModel = new DefaultListModel<Object>();
          rightListModel =
new DefaultListModel<Object>();

         
// Add items to the list models
         
for(int i=0; i<5; ++i)
               
leftListModel.addElement("Item " + i);
         
for(int i=5; i<10; ++i)
               
rightListModel.addElement("Item " + i);

         
// Create the lists
         
leftList = new JList<Object>(leftListModel);
          rightList =
new JList<Object>(rightListModel);

         
// Register the selection listener
         
leftList.addListSelectionListener(this);
          rightList.addListSelectionListener
(this);

         
// Wrap scroll panes around the lists
         
leftScrollPane = new JScrollPane(leftList);
          rightScrollPane =
new JScrollPane(rightList);

         
// Set the size of the scroll panes
         
Dimension dimension = new Dimension(100, 150);
          leftScrollPane.setPreferredSize
(dimension);
          leftScrollPane.setMinimumSize
(dimension);
          rightScrollPane.setPreferredSize
(dimension);
          rightScrollPane.setMinimumSize
(dimension);
   
}


   
private void init() {
         
setTitle("Lists");
          setSize
(450, 200);
          setLocationRelativeTo
(null);
   
}


   
public void valueChanged(ListSelectionEvent e) {
         
if(e.getValueIsAdjusting() == false){
               
if(e.getSource().equals(leftList))
                     
moveRightButton.setEnabled(true);
               
else
                     
moveLeftButton.setEnabled(true);
         
}
    }


   
public static void main(String[] args){
         
SwingUtilities.invokeLater(new Runnable() {
               
public void run() {
                     
new Lists2();
               
}
          })
;
   
}
}


You are here :  JavaPerspective.com  >   Intermediate Tutorials  >   5. Graphical User Interfaces  >   5.21. Lists
Next tutorial :  JavaPerspective.com  >   Intermediate Tutorials  >   5. Graphical User Interfaces  >   5.22. Spinners

Copyright © 2013 - 2016. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7