JList that allows multiple selections. - Java Swing

Java examples for Swing:JList

Description

JList that allows multiple selections.

Demo Code

import java.awt.FlowLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;

class MultipleSelectionFrame extends JFrame {
  private  JList<String> colorJList= new JList(); // list to hold color names
  private  JList<String> copyJList= new JList(); // list to hold copied names
  private JButton copyJButton; // button to copy selected names
  private static final String[] colorNames = { "Black", "Blue", "Cyan",
      "Dark Gray", "Gray", "Green", "Light Gray", "Magenta", "Orange", "Pink",
      "Red", "White", "Yellow" };

  public MultipleSelectionFrame() {
    setLayout(new FlowLayout());

    colorJList = new JList<String>(colorNames); // list of color names
    colorJList.setVisibleRowCount(5); // show five rows
    colorJList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    add(new JScrollPane(colorJList)); // add list with scrollpane

    copyJButton = new JButton("Copy >>>");
    copyJButton.addActionListener(e ->
    // place selected values in copyJList
        copyJList.setListData(colorJList.getSelectedValuesList().toArray(
            new String[0])));

    add(copyJButton); // add copy button to JFrame

    copyJList = new JList<String>(); // list to hold copied color names
    copyJList.setVisibleRowCount(5); // show 5 rows
    copyJList.setFixedCellWidth(100); // set width
    copyJList.setFixedCellHeight(15); // set height
    copyJList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
    add(new JScrollPane(copyJList)); // add list with scrollpane
  }// w  ww  .j a va2  s.  co m
}

public class Main {
  public static void main(String[] args) {
    MultipleSelectionFrame multipleSelectionFrame = new MultipleSelectionFrame();
    multipleSelectionFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    multipleSelectionFrame.setSize(350, 150);
    multipleSelectionFrame.setVisible(true);
  }
}

Related Tutorials