JList with ListSelectionModel.SINGLE_INTERVAL_SELECTION and ListSelectionModel.SINGLE_SELECTION

A JList allows the user to select multiple ranges of items within the list, but you can change this behavior by calling setSelectionMode( ), which is defined by JList. It is shown here:

void setSelectionMode(int mode)

Here, mode specifies the selection mode. It must be one of these values defined by ListSelectionModel:

SINGLE_SELECTION
SINGLE_INTERVAL_SELECTION
MULTIPLE_INTERVAL_SELECTION

The default, multiple-interval selection, lets the user select multiple ranges of items within a list. With single-interval selection, the user can select one range of items. With single selection, the user can select only a single item. Of course, a single item can be selected in the other
two modes, too. It’s just that they also allow a range to be selected.

Program

fdgdf

 

 

 

Program Source

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListSelectionModel;
import javax.swing.JScrollPane;
import java.awt.Dimension;
import java.awt.FlowLayout;

class Frame extends JFrame {

    Frame()
    {
        setTitle("JList : SINGLE_INTERVAL_SELECTION and SINGLE_SELECTION");
        setLayout(new FlowLayout());
        setJList1();
        setJList2();
        setSize(700,250);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
 
    private void setJList1()
    {
        String[] names = {"Windows","Ubuntu","Macintosh","Linux","Fedora"};
        JList jl = new JList(names);
        jl.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        JScrollPane js = new JScrollPane(jl);
        js.setPreferredSize(new Dimension(200,200));
        add(new JLabel("SINGLE_INTERVAL_SELECTION"));
        add(js);
    }
 
    private void setJList2()
    {
        String[] names = {"Symbian","Android","Apple iOS","BlackBerry","Windows Mobile"};
        JList jl = new JList(names);
        jl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane js = new JScrollPane(jl);
        js.setPreferredSize(new Dimension(200,200));
        add(new JLabel("SINGLE_SELECTION"));
        add(js);
    }
}

public class Javaapp {

    public static void main(String[] args) {
     
       Frame fr = new Frame();
    }
}

Leave a Comment