move JList Item Down - Java Swing

Java examples for Swing:JList

Description

move JList Item Down

Demo Code


//package com.java2s;

import javax.swing.DefaultListModel;
import javax.swing.JList;

public class Main {
    public static DefaultListModel<String> moveItemDown(
            DefaultListModel<String> listModel, JList<String> list) {
        // Check if selected index is in bounds
        if (list.getSelectedIndex() >= 0) {
            // Check if destination index is inbounds
            if (list.getSelectedIndex() + 1 < listModel.toArray().length) {
                // Copy selected item to a lower index;
                listModel.add(list.getSelectedIndex() + 2,
                        listModel.get(list.getSelectedIndex()));
                int newIndex = list.getSelectedIndex() + 1;
                // Remove the item at the selected index
                listModel.remove(list.getSelectedIndex());
                // Select the index the item is moved to
                list.setSelectedIndex(newIndex);
            }/*from  w ww . j  a  v  a  2 s.  c om*/
        }
        return listModel;
    }
}

Related Tutorials