Set selection index in Java

Description

The following code shows how to set selection index.

Example


  /*from  www  . j av a 2 s .  com*/
import java.awt.BorderLayout;

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

public class Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Modifying Model");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JList jlist = new JList(new String[]{"A","B","C","v","a","d","java2s.com"});
    jlist.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
    
    jlist.getSelectionModel().setAnchorSelectionIndex(0);   
    jlist.getSelectionModel().setLeadSelectionIndex(2);
    
    JScrollPane scrollPane1 = new JScrollPane(jlist);
    frame.add(scrollPane1, BorderLayout.CENTER);

    frame.setSize(640, 300);
    frame.setVisible(true);
  }
}

The code above generates the following result.

Set selection index in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer