Java JList set to multiple selections.

Description

Java JList set to multiple selections.


// JList that allows multiple selections.
import java.awt.FlowLayout;

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

public class Main extends JFrame {
  private final JList<String> colorJList; // list to hold color names
  private final JList<String> copyJList; // 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"};

  // Main constructor
  public Main() {
    super("Multiple Selection Lists");
    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");

    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);
    //from w w w  .  ja  v a2s. com
    copyJButton.addActionListener(e->{
      // place selected values in copyJList
      copyJList.setListData(colorJList.getSelectedValuesList().toArray(new String[0]));
    });

    
    add(new JScrollPane(copyJList)); // add list with scroll pane
  }

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



PreviousNext

Related