How many types of selection modes for a JList in Java?

A JList is a component that can extend JComponent class used to display a list of objects that allows the user to select one or more items.

There are three types of selection modes for a JList in Java

  • ListSelectionModel.SINGLE_SELECTION: Only one list index can be selected at a time.
  • ListSelectionModel.SINGLE_INTERVAL_SELECTION: Only one contiguous interval can be selected at a time.
  • ListSelectionModel.MULTIPLE_INTERVAL_SELECTION: In this mode, there is no restriction on what can be selected. This is a default mode.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JListSelectionModeTest extends JFrame implements ActionListener {
   private JList list;
   private DefaultListModel listModel;
   public JListSelectionModeTest() {
      setTitle("JListSelectionMode Test");
      setLayout(new BorderLayout());
      listModel = new DefaultListModel();
      for (int i = 1; i ListSelectionModel.SINGLE_SELECTION);
      else if (ae.getActionCommand().equals("SINGLE_INTERVAL_SELECTION"))
         list.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
      else if (ae.getActionCommand().equals("MULTIPLE_INTERVAL_SELECTION"))
         list.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
   }
   public static void main(String[] args) {
      new JListSelectionModeTest();
   }
}

Output

Updated on: 2020-02-10T07:01:22+05:30

940 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements