所以我有一个GUI组件,其中JList依赖于任务的ArrayList。此Task对象具有特定索引,我希望JList反映该特定顺序。到目前为止这没问题。 问题是我希望用户将对象拖放到JList中以更改顺序。我希望ArrayList(支持Jlist)也能反映这些变化。
这是我的TransferHandler类:
class ListItemTransferHandler extends TransferHandler {
private final DataFlavor localObjectFlavor;
private Object[] transferedObjects = null;
public ListItemTransferHandler() {
localObjectFlavor = new ActivationDataFlavor(Object[].class, DataFlavor.javaJVMLocalObjectMimeType, "Array of items");
}
@SuppressWarnings("deprecation")
@Override
protected Transferable createTransferable(JComponent c) {
JList list = (JList) c;
indices = list.getSelectedIndices();
transferedObjects = list.getSelectedValues();
return new DataHandler(transferedObjects, localObjectFlavor.getMimeType());
}
@Override
public boolean canImport(TransferSupport info) {
if (!info.isDrop() || !info.isDataFlavorSupported(localObjectFlavor)) {
return false;
}
return true;
}
@Override
public int getSourceActions(JComponent c) {
return MOVE; // TransferHandler.COPY_OR_MOVE;
}
@SuppressWarnings("unchecked")
@Override
public boolean importData(TransferSupport info) {
if (!canImport(info)) {
return false;
}
JList target = (JList) info.getComponent();
JList.DropLocation dl = (JList.DropLocation) info.getDropLocation();
DefaultListModel listModel = (DefaultListModel) target.getModel();
int index = dl.getIndex();
int max = listModel.getSize();
if (index < 0 || index > max) {
index = max;
}
addIndex = index;
try {
Object[] values = (Object[]) info.getTransferable().getTransferData(localObjectFlavor);
addCount = values.length;
for (int i = 0; i < values.length; i++) {
int idx = index++;
listModel.add(idx, values[i]);
target.addSelectionInterval(idx, idx);
}
return true;
} catch (UnsupportedFlavorException ufe) {
ufe.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
return false;
}
@Override
protected void exportDone(JComponent c, Transferable data, int action) {
cleanup(c, action == MOVE);
}
private void cleanup(JComponent c, boolean remove) {
if (remove && indices != null) {
JList source = (JList) c;
DefaultListModel model = (DefaultListModel) source.getModel();
if (addCount > 0) {
// http://java-swing-tips.googlecode.com/svn/trunk/DnDReorderList/src/java/example/MainPanel.java
for (int i = 0; i < indices.length; i++) {
if (indices[i] >= addIndex) {
indices[i] += addCount;
}
}
}
for (int i = indices.length - 1; i >= 0; i--) {
model.remove(indices[i]);
}
}
indices = null;
addCount = 0;
addIndex = -1;
}
private int[] indices = null;
private int addIndex = -1; // Location where items were added
private int addCount = 0; // Number of items added.
}
我如何实现此功能?我想这会有所帮助,但Task对象实现Comparable进行排序。