Evgenij Reznik
Evgenij Reznik

Reputation: 18594

Sorting tasks by priority

How can I sort things by priority in a JList?
For example I have several tasks like "Washing, Cooking, Laundry" and I want to be able to sort them with the mouse (GUI) with the most important at the top.
This is my code so far:

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class Test extends JFrame implements ActionListener {

    JPanel pLeft = new JPanel();
    JPanel pRight = new JPanel();
    String data[] = {
        "Item 1",
        "Item 2",
        "Item 3",
        "Item 4",
        "Item 5"
    };
    DefaultListModel model = new DefaultListModel();
    JList list = new JList(model);
    JScrollPane listScroller = new JScrollPane(list);
    JButton bUp = new JButton("UP");
    JButton bDown = new JButton("DOWN");

    public Test() {
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setBounds(300, 100, 300, 200);
        this.setVisible(true);
        this.setLayout(new BorderLayout());
        pRight.setLayout(new BorderLayout());

        this.add(pLeft, BorderLayout.WEST);
        this.add(pRight, BorderLayout.EAST);

        listScroller.setPreferredSize(new Dimension(150, 150));
        pLeft.add(listScroller);

        pRight.add(bUp, BorderLayout.NORTH);
        pRight.add(bDown, BorderLayout.SOUTH);

        bUp.addActionListener(this);
        bDown.addActionListener(this);

        for (int i = 0; i < data.length; i++) {
            model.add(i, data[i]);
        }
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        Object source = ae.getSource();
        if (source == bUp) {
            model.setElementAt(model.getElementAt(list.getSelectedIndex()), list.getSelectedIndex() + 1);
        }
        if (source == bDown) {
            model.setElementAt(model.getElementAt(list.getSelectedIndex()), list.getSelectedIndex() - 1);
        }

    }

    public static void main(String[] args) {
        Test test = new Test();
    }
}

But instead of just "changing" its position, the old item is just replaced by the new one.

Upvotes: 0

Views: 296

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168825

Use a JList. See How to Use Lists for more details.

The Drag'n'Drop package is where to look for the functionality to re-order the list. See the Drag and Drop and Data Transfer lesson of the Java Tutorial for how to use the D'n'D API.

Upvotes: 3

Related Questions