SWING - JList Class

The class JList is a component which displays a list of objects and allows the user to select one or more items. A separate model, ListModel, maintains the contents of the list.
Following is the declaration for javax.swing.JList class −
public class JList
   extends JComponent
      implements Scrollable, Accessible

Following are the fields for javax.swing.JList class −
static int HORIZONTAL_WRAP − Indicates a "newspaper style" layout with cells flowing horizontally then vertically.
static int HORIZONTAL_WRAP − Indicates a "newspaper style" layout with cells flowing horizontally then vertically.
static int VERTICAL − Indicates a vertical layout of cells, in a single column; the default layout.
static int VERTICAL − Indicates a vertical layout of cells, in a single column; the default layout.
static int VERTICAL_WRAP − Indicates a "newspaper style" layout with cells flowing vertically then horizontally.
static int VERTICAL_WRAP − Indicates a "newspaper style" layout with cells flowing vertically then horizontally.
JList()
Constructs a JList with an empty, read-only, model.
JList(ListModel dataModel)
Constructs a JList that displays elements from the specified, non-null, model.
JList(Object[] listData)
Constructs a JList that displays the elements in the specified array.
JList(Vector<?> listData)
Constructs a JList that displays the elements in the specified Vector.
void addListSelectionListener(ListSelectionListener listener)
Adds a listener to the list, to be notified each time a change to the selection occurs; the preferred way of listening for selection state changes.
void addSelectionInterval(int anchor, int lead)
Sets the selection to be the union of the specified interval with the current selection.
void clearSelection()
Clears the selection; after calling this method, isSelectionEmpty will return true.
protected  ListSelectionModel	createSelectionModel()
Returns an instance of DefaultListSelectionModel; called during construction to initialize the list's selection model property.
void ensureIndexIsVisible(int index)
Scrolls the list within an enclosing viewport to make the specified cell completely visible.
protected void fireSelectionValueChanged(int firstIndex, int lastIndex, boolean isAdjusting)
Notifies ListSelectionListeners added directly to the list of selection changes made to the selection model.
AccessibleContext getAccessibleContext()
Gets the AccessibleContext associated with this JList.
int getAnchorSelectionIndex()
Returns the anchor selection index.
Rectangle getCellBounds(int index0, int index1)
Returns the bounding rectangle, in the list's coordinate system, for the range of cells specified by the two indices.
ListCellRenderer getCellRenderer()
Returns the object responsible for painting list items.
boolean getDragEnabled()
Returns whether or not automatic drag handling is enabled.
JList.DropLocation getDropLocation()
Returns the location that this component should visually indicate as the drop location during a DnD operation over the component, or null if no location is to currently be shown.
DropMode getDropMode()
Returns the drop mode for this component.
int getFirstVisibleIndex()
Returns the smallest list index that is currently visible.
int getFixedCellHeight()
Returns the value of the fixedCellHeight property.
int getFixedCellWidth()
Returns the value of the fixedCellWidth property.
int getLastVisibleIndex()
Returns the largest list index that is currently visible.
int getLayoutOrientation()
Returns the layout orientation property for the list: VERTICAL if the layout is a single column of cells, VERTICAL_WRAP if the layout is "newspaper style" with the content flowing vertically then horizontally, or HORIZONTAL_WRAP if the layout is "newspaper style" with the content flowing horizontally then vertically.
int getLeadSelectionIndex()
Returns the lead selection index.
ListSelectionListener[] getListSelectionListeners()
Returns an array of all the ListSelectionListeners added to this JList by way of addListSelectionListener.
int getMaxSelectionIndex()
Returns the largest selected cell index, or -1 if the selection is empty.
int getMinSelectionIndex()
Returns the smallest selected cell index, or -1 if the selection is empty.
ListModel getModel()
Returns the data model that holds the list of items displayed by the JList component.
int getNextMatch(String prefix, int startIndex, Position.Bias bias)
Returns the next list element whose toString value starts with the given prefix.
Dimension getPreferredScrollableViewportSize()
Computes the size of viewport needed to display visibleRowCount rows.
Object getPrototypeCellValue()
Returns the "prototypical" cell value -- a value used to calculate a fixed width and height for cells.
int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction)
Returns the distance to scroll to expose the next or previous block.
boolean getScrollableTracksViewportHeight()
Returns true if this JList is displayed in a JViewport and the viewport is taller than the list's preferred height, or if the layout orientation is VERTICAL_WRAP and visibleRowCount <= 0; otherwise returns false.
boolean getScrollableTracksViewportWidth()
Returns true if this JList is displayed in a JViewport and the viewport is wider than the list's preferred width, or if the layout orientation is HORIZONTAL_WRAP and visibleRowCount <= 0; otherwise returns false.
int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
Returns the distance to scroll to expose the next or previous row (for vertical scrolling) or column (for horizontal scrolling).
int getSelectedIndex()
Returns the smallest selected cell index; the selection when only a single item is selected in the list.
int[]	getSelectedIndices()
Returns an array of all of the selected indices, in an increasing order.
Object getSelectedValue()
Returns the value for the smallest selected cell index; the selected value when only a single item is selected in the list.
Object[] getSelectedValues()
Returns an array of all the selected values, in an increasing order based on their indices in the list.
Color getSelectionBackground()
Returns the color used to draw the background of selected items.
Color getSelectionForeground()
Returns the color used to draw the foreground of selected items.
int getSelectionMode()
Returns the current selection mode for the list.
ListSelectionModel getSelectionModel()
Returns the current selection model.
String getToolTipText(MouseEvent event)
Returns the tooltip text to be used for the given event.
ListUI getUI()
Returns the ListUI, the look and feel object that renders this component.
String getUIClassID()
Returns "ListUI", the UIDefaults key used to look up the name of the javax.swing.plaf.ListUI class that defines the look and feel for this component.
boolean getValueIsAdjusting()
Returns the value of the selection model's isAdjusting property.
int getVisibleRowCount()
Returns the value of the visibleRowCount property.
Point indexToLocation(int index)
Returns the origin of the specified item in the list's coordinate system.
boolean isSelectedIndex(int index)
Returns true, if the specified index is selected, else false.
boolean isSelectionEmpty()
Returns true, if nothing is selected, else false.
int locationToIndex(Point location)
Returns the cell index closest to the given location in the list's coordinate system.
protected String paramString()
Returns a String representation of this JList.
void removeListSelectionListener(ListSelectionListener listener)
Removes a selection listener from the list.
void removeSelectionInterval(int index0, int index1)
Sets the selection to be the set difference of the specified interval and the current selection.
void setCellRenderer(ListCellRenderer cellRenderer)
Sets the delegate that is used to paint each cell in the list.
void setDragEnabled(boolean b)
Turns the automatic drag handling on or off.
void setDropMode(DropMode dropMode)
Sets the drop mode for this component.
void setFixedCellHeight(int height)
Sets a fixed value to be used for the height of every cell in the list.
void setFixedCellWidth(int width)
Sets a fixed value to be used for the width of every cell in the list.
void setLayoutOrientation(int layoutOrientation)
Defines the way list cells are layed out.
void setListData(Object[] listData)
Constructs a read-only ListModel from an array of objects, and calls setModel with this model.
void setListData(Vector<?> listData)
Constructs a read-only ListModel from a Vector and calls setModel with this model.
void setModel(ListModel model)
Sets the model that represents the contents or "value" of the list, notifies property change listeners, and then clears the list's selection.
void setPrototypeCellValue(Object prototypeCellValue)
Sets the prototypeCellValue property, and then (if the new value is non-null), computes the fixedCellWidth and fixedCellHeight properties by requesting the cell renderer component for the given value (and index 0) from the cell renderer, and using that component's preferred size.
void setSelectedIndex(int index)
Selects a single cell.
void setSelectedIndices(int[] indices)
Changes the selection to be the set of indices specified by the given array.
void setSelectedValue(Object anObject, boolean shouldScroll)
Selects the specified object from the list.
void setSelectionBackground(Color selectionBackground)
Sets the color used to draw the background of the selected items, which cell renderers can use to fill the selected cells.
void setSelectionForeground(Color selectionForeground)
Sets the color used to draw the foreground of the selected items, which cell renderers can use to render text and graphics.
void setSelectionInterval(int anchor, int lead)
Selects the specified interval.
void setSelectionMode(int selectionMode)
Sets the selection mode for the list.
void setSelectionModel(ListSelectionModel selectionModel)
Sets the selectionModel for the list to a non-null ListSelectionModel implementation.
void setUI(ListUI ui)
Sets the ListUI, the look and feel object that renders this component.
void setValueIsAdjusting(boolean b)
Sets the selection model's valueIsAdjusting property.
void setVisibleRowCount(int visibleRowCount)
Sets the visibleRowCount property, which has different meanings depending on the layout orientation: For a VERTICAL layout orientation, this sets the preferred number of rows to display without requiring scrolling; for other orientations, it affects the wrapping of cells.
void updateUI()
Resets the ListUI property by setting it to the value provided by the current look and feel.
This class inherits methods from the following classes −
javax.swing.JComponent
java.awt.Container
java.awt.Component
java.lang.Object
Create the following Java program using any editor of your choice in say D:/ > SWING > com > tutorialspoint > gui >
SwingControlDemo.java
package com.tutorialspoint.gui;
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
 
public class SwingControlDemo {
   private JFrame mainFrame;
   private JLabel headerLabel;
   private JLabel statusLabel;
   private JPanel controlPanel;
   
   public SwingControlDemo(){
      prepareGUI();
   }
   public static void main(String[] args){
      SwingControlDemo  swingControlDemo = new SwingControlDemo();      
      swingControlDemo.showListDemo();
   }
   private void prepareGUI(){
      mainFrame = new JFrame("Java Swing Examples");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      
      mainFrame.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent windowEvent){
            System.exit(0);
         }        
      });    
      headerLabel = new JLabel("", JLabel.CENTER);        
      statusLabel = new JLabel("",JLabel.CENTER);    
      statusLabel.setSize(350,100);

      controlPanel = new JPanel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
   }
   private void showListDemo(){                                       
      headerLabel.setText("Control in action: JList"); 
      final DefaultListModel fruitsName = new DefaultListModel();

      fruitsName.addElement("Apple");
      fruitsName.addElement("Grapes");
      fruitsName.addElement("Mango");
      fruitsName.addElement("Peer");

      final JList fruitList = new JList(fruitsName);
      fruitList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
      fruitList.setSelectedIndex(0);
      fruitList.setVisibleRowCount(3);        

      JScrollPane fruitListScrollPane = new JScrollPane(fruitList);    
      final DefaultListModel vegName = new DefaultListModel();

      vegName.addElement("Lady Finger");
      vegName.addElement("Onion");
      vegName.addElement("Potato");
      vegName.addElement("Tomato");

      final JList vegList = new JList(vegName);
      vegList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
      vegList.setSelectedIndex(0);
      vegList.setVisibleRowCount(3);        

      JScrollPane vegListScrollPane = new JScrollPane(vegList);       
      JButton showButton = new JButton("Show");

      showButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) { 
            String data = "";
            if (fruitList.getSelectedIndex() != -1) {                     
               data = "Fruits Selected: " + fruitList.getSelectedValue(); 
               statusLabel.setText(data);
            }
            if(vegList.getSelectedIndex() != -1){
               data += " Vegetables selected: ";
               for(Object vegetable:vegList.getSelectedValues()){
                  data += vegetable + " ";
               }
            }
            statusLabel.setText(data);
         }
      }); 
      controlPanel.add(fruitListScrollPane);    
      controlPanel.add(vegListScrollPane);    
      controlPanel.add(showButton);    
	  
      mainFrame.setVisible(true);             
   }
}
Compile the program using the command prompt. Go to D:/ > SWING and type the following command.
D:\SWING>javac com\tutorialspoint\gui\SwingControlDemo.java

If no error occurs, it means the compilation is successful. Run the program using the following command.
D:\SWING>java com.tutorialspoint.gui.SwingControlDemo

Verify the following output.

    30 Lectures 
     3.5 hours 

 Pranjal Srivastava

    13 Lectures 
     1 hours 

 Pranjal Srivastava

    25 Lectures 
     4.5 hours 

 Emenwa Global, Ejike IfeanyiChukwu

    14 Lectures 
     1.5 hours 

 Travis Rose

    14 Lectures 
     1 hours 

 Travis Rose
 Print
 Add Notes
 Bookmark this page