如何在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();
}
}
但不是仅仅“改变”它的位置,旧项目就会被新项目取代。
答案 0 :(得分:3)
使用JList
。有关详细信息,请参阅How to Use Lists。
Drag'n'Drop包可以在哪里查找重新排序列表的功能。有关如何使用D'n'D API的信息,请参阅Java教程的Drag and Drop and Data Transfer课程。