Example usage for javax.swing JList setSelectionInterval

List of usage examples for javax.swing JList setSelectionInterval

Introduction

In this page you can find the example usage for javax.swing JList setSelectionInterval.

Prototype

public void setSelectionInterval(int anchor, int lead) 

Source Link

Document

Selects the specified interval.

Usage

From source file:util.ui.UiUtilities.java

/**
 * Move selected Items in the JList/*from w w  w.  j a  v a2 s . c  om*/
 *
 * @param list
 *          Move Items in this List
 * @param nrRows
 *          Move Items nrRows up/down
 */
public static void moveSelectedItems(JList list, int nrRows) {
    DefaultListModel model = (DefaultListModel) list.getModel();

    // get the selection
    int[] selection = list.getSelectedIndices();
    if (selection.length == 0) {
        return;
    }

    // Remove the selected items
    Object[] items = new Object[selection.length];
    for (int i = selection.length - 1; i >= 0; i--) {
        items[i] = model.remove(selection[i]);
    }

    // insert the elements at the target position
    int targetPos = selection[0] + nrRows;
    targetPos = Math.max(targetPos, 0);
    targetPos = Math.min(targetPos, model.getSize());
    for (int i = 0; i < items.length; i++) {
        model.add(targetPos + i, items[i]);
    }

    // change selection of the toList
    list.setSelectionInterval(targetPos, targetPos + selection.length - 1);

    // ensure the selection is visible
    list.ensureIndexIsVisible(list.getMaxSelectionIndex());
    list.ensureIndexIsVisible(list.getMinSelectionIndex());
}