Java Swing Tutorial - Java DefaultListSelectionModel .insertIndexInterval (int index, int length, boolean before)








Syntax

DefaultListSelectionModel.insertIndexInterval(int index, int length, boolean before) has the following syntax.

public void insertIndexInterval(int index,   int length,   boolean before)

Example

In the following code shows how to use DefaultListSelectionModel.insertIndexInterval(int index, int length, boolean before) method.

import java.awt.BorderLayout;
//from   w  w w .  ja  va  2 s .  c  o  m
import javax.swing.DefaultListSelectionModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class Main extends JPanel {

  String label[] = { "Zero", "One", "Two" };

  JList list;

  public Main() {
    setLayout(new BorderLayout());

    list = new JList(label);
    JScrollPane pane = new JScrollPane(list);

    DefaultListSelectionModel m = new DefaultListSelectionModel();
    
    m.addListSelectionListener(new ListSelectionListener() {
      public void valueChanged(ListSelectionEvent e) {
        System.out.println(e.toString());
      }
    });
    
    list.setSelectionModel(m);

    m.insertIndexInterval(1,2,true);
    
    
    add(pane, BorderLayout.NORTH);
  }

  public static void main(String s[]) {
    JFrame frame = new JFrame("List Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(new Main());
    frame.pack();
    frame.setVisible(true);
  }

}