Java JList Basics with Examples


JList is used to display an array of vectors in Java. It comes with Swing package and also it inherits JComponent Class. JList displays a set of elements and allows the user to make the selection for one or more items. You can also check selected elements of the list using different methods given below.

JList Constructors

Following are the constructors for JList in Java:

  • JList(): Used to create empty blank list.
  • JList(arry[] listData): Used to create new List with elements provided by the array.
  • JList(ListModel<arry> dataModel): Creates new List with provided list Model.

Commonly Used Methods

Following is the list of commonly used methods:

Name Description
getSelectedValue() It will return the value of element selected by user.
getSelectedIndex() It will return the index of element selected by user.
setSelectedIndex(int i) Sets value of i as selected index.
setListData(E [ ] le) Sets the elements of le replacing existing.
setSelectionBackground(Color c) It sets the background color for selected item.
setSelectionForeground(Color c) Sets the foreground color for selected item.
setVisibleRowCount(int v) Sets the visibleRowCount property to v
setSelectedValue(Object a, boolean s) It sets the value to selected element
setSelectedIndices(int[] i) Sets all the items from given indices array as selected
setListData(Vector l) constructs a read only list model with provided vector
setLayoutOrientation(int l) sets orientation of layout
setFixedCellWidth(int width) Changes the cell width
setFixedCellHeight(int height) Changes the cell height
isSelectedIndex(int i) Returns true if index provided is selected
indexToLocation(int i) It returns the origin of given item
getToolTipText(MouseEvent e) Returns the tooltip text for given event
getSelectedValuesList() Returns the list of selected item values
getSelectedIndices() It returns the list of selected indices in incresing order
getMinSelectionIndex() returns the smallest index of selected value
getMaxSelectionIndex() returns the biggest index of selected value
getListSelectionListeners() It returns the listeners of list
getLastVisibleIndex() returns the index of last visible element
getDragEnabled() returns true if drag enabled
addListSelectionListener(listSelectionListener l) adds listSelectionListener l to list

Add Item to JList

To add an element, you should add it first to the ListModel then set the ListModel to JList.

    
// Create a model
DefaultListModel defaultListModel = new DefaultListModel();
    
// add element to model
defaultListModel.addElement("first element");

// add element to model
defaultListModel.addElement("second element");
    
// Now create a list and pass defaultModel to constructor
JList list = new JList(defaultListModel);

Remove Item from JList

To remove an element, You should remove it from the ListModel:

    
// Create a model
DefaultListModel defaultListModel = new DefaultListModel();
    
// add element to model
defaultListModel.addElement("first element");

// add element to model
defaultListModel.addElement("second element");
    
// Now create a list and pass defaultModel to constructor
JList list = new JList(defaultListModel);

// add another element to model
defaultListModel.addElement("third element");

// remove element from model
defaultListModel.removeElementAt(0);

Set Listener

You can add a listener in the following way:

newJlist.addListSelectionListener(new ListSelectionListener() {
    @Override
    public void valueChanged(ListSelectionEvent e)
    {
        // Your Logic Here

        if(!e.getValueIsAdjusting()) {
            final List selectedValuesList = newJlist.getSelectedValuesList();
            System.out.println(selectedValuesList);
        }
    }
});

Examples

Following are the examples for JList. The first example is the simple example and in the second example on more element Button is added.

Example 1’st

// java Program to create JList 
import javax.swing.*;
import java.awt.event.*; 
import java.awt.*; 
public class Demo extends JFrame  
{ 
    //frame 
    static JFrame jframe; 
    //lists
    static JList jlist; 

    public static void main(String[] args) 
    { 
        //creating a new frame  
        jframe = new JFrame("frame"); 
        //creating a panel 
        JPanel panel =new JPanel(); 
        
        //creating a new label 
        JLabel label= new JLabel("Select the month of year"); 
  
        //String Array
        String month[]= { "January","February","March","April","May","June","July",
 "August","September","October","November","December"}; 
          
        //creating list 
        jlist = new JList(month); 
        //setting a selected index 
        jlist.setSelectedIndex(3); 
          
        //adding jlist to panel
        panel.add(jlist); 
        jframe.add(label);
        jframe.add(panel);
        // setting up the default size
        jframe.setSize(400,400); 
        jframe.show(); 
    } 
}

Below is the output for the above program which shows the default screen of the program in which the list item April is selected by default:

"<yoastmark

Example 2’nd

 
import javax.swing.*;  
import java.awt.event.*;  
public class Demo2  
{  
    public static void main(String args[]){  
        JFrame frame= new JFrame();  
        
        // set up label
        final JLabel label = new JLabel();          
        label.setSize(500,100);  
        
        // set up button
        JButton button=new JButton("SHOW");  
        button.setBounds(200,150,80,30);  
        
        // creating listModel for OS type list
        final DefaultListModel listModel1 = new DefaultListModel<>();  
        listModel1.addElement("Windows");  
        listModel1.addElement("MacOS");  
        listModel1.addElement("Linux");
        
        // creating os type list
        final JList list1 = new JList<>(listModel1);  
        list1.setBounds(100,100, 75,75);
        
        // creating listModel for OS list
        DefaultListModel listModel2 = new DefaultListModel<>();  
        listModel2.addElement("Windows 10");  
        listModel2.addElement("Ubuntu");  
        listModel2.addElement("MacOS 10");  
        listModel2.addElement("Linux Mint");
        
        // creating os list
        final JList list2 = new JList<>(listModel2);  
        list2.setBounds(100,200, 75,75);  
        
        // add elements to frame
        frame.add(list1); 
        frame.add(list2); 
        frame.add(button); 
        frame.add(label);
        
        // set display config for frame
        frame.setSize(650,650);  
        frame.setLayout(null);  
        frame.setVisible(true);
        
        // adding listener for button
        button.addActionListener(new ActionListener() {  
            
            public void actionPerformed(ActionEvent e) {   
                String data = "";  
                if (list1.getSelectedIndex() != -1) {                       
                    data = "OS Type Selected: " + list1.getSelectedValue();   
                    label.setText(data);  
                }  
                if(list2.getSelectedIndex() != -1){  
                    data += ", Oprating System Selected: ";  
                    for(Object f :list2.getSelectedValues()){  
                       data += f + " ";  
                    }  
                }  
                label.setText(data);  
            }
            
        });     
    }
    
}

Below is the output for the above program. The first screenshot shows the default screen after running program And the second screen shows output after clicking on SHOW button:

"<yoastmark

"<yoastmark