如何在 JList 中按优先级排序?
例如,我有几个任务,例如“洗涤、烹饪、洗衣”,我希望能够使用鼠标 (GUI) 对它们进行排序,最重要的在顶部。
到目前为止,这是我的代码:
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();
}
}
但不是只是“改变”它的位置,旧项目只是被新项目替换。