In the previous tutorials, we have discussed about JList with single item selection. In this tutorial, I am going to show a most useful example of how to use Java JList Multiple Selection mode.

Java JList Multiple Selection :

I am going to reuse the previous example here and enable multiple selection modes and copy the selected items to another JList.

JListCopyDemo.java
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import com.onlinetutorialspoint.swing.JListDemo;


public class JListCopyDemo extends JFrame {
    private JList jList;
    private JList jListForCopy;
    private JButton copyButton;
    private static final String[] listItems = { "BLUE", "BLACK", "CYAN",
            "GREEN", "GRAY", "RED", "WHITE" };
    private static final Color[] colors = { Color.BLUE, Color.BLACK,
            Color.CYAN, Color.GREEN, Color.GRAY, Color.RED, Color.WHITE };

    public JListCopyDemo() {
        super("JList Demo");
        setLayout(new FlowLayout());

        jList = new JList(listItems);
        jList.setFixedCellHeight(15);
        jList.setFixedCellWidth(100);
        jList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        jList.setVisibleRowCount(4);
        add(new JScrollPane(jList));
        
        copyButton = new JButton("Copy>>>");
        
        copyButton.addActionListener(new ActionListener() {
            
            @Override
            public void actionPerformed(ActionEvent e) {
                jListForCopy.setListData(jList.getSelectedValues());
            }
        });
        
        add(copyButton);
        jListForCopy = new JList();
        jListForCopy.setFixedCellHeight(15);
        jListForCopy.setFixedCellWidth(100);
        jList.setVisibleRowCount(4);
        jList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
        add(new JScrollPane(jListForCopy));
    }
    public static void main(String[] args) {
        JListCopyDemo jListDemo = new JListCopyDemo();
        jListDemo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jListDemo.setSize(350, 150);
        jListDemo.setVisible(true);
    }
}

Output :

Java JList Multiple Selection

JList Multiple Selection :

Java JList Multiple Selection 1

Copy JList Multiple Selection :

Java JList Multiple Selection 2

Happy Learning 🙂