DefaultListModel move Item Up - Java Swing

Java examples for Swing:JList

Description

DefaultListModel move Item Up

Demo Code


//package com.java2s;

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

public class Main {
    public static DefaultListModel<String> moveItemUp(
            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() != 0) {
                // Copy selected item to a lower index;
                listModel.add(list.getSelectedIndex() - 1,
                        listModel.get(list.getSelectedIndex()));
                int newIndex = list.getSelectedIndex() - 2;
                // Remove the item at the selected index
                listModel.remove(list.getSelectedIndex());
                // Select the index the item is moved to
                list.setSelectedIndex(newIndex);
            }//from   w  w  w  .jav  a 2 s  .co m
        }
        return listModel;
    }
}

Related Tutorials