我在使用Java進行拖放時遇到了一些問題。從JList/JTable拖放到對象
這很簡單我想,我只是想允許拖放自定義對象從JList到另一個。
我讀過很多關於資源的,現在我有這樣的代碼:
listPlantation = new JList();
plantationList = Plantation.plantations;
DefaultListModel dlm = new DefaultListModel();
Iterator<Plantation> it = plantationList.iterator();
// Here I instance my ListModel with my custom Element
while(it.hasNext())
{
Plantation obj = it.next();
if(obj !=null)
{
dlm.addElement(obj);
}
}
// Yeah of course I want Drag Enable :)
listPlantation.setDragEnabled(true);
// Ok let's create my Transferhandler
listPlantation.setTransferHandler(new TransferHandler() {
@Override
protected Transferable createTransferable(JComponent c) {
JList list = (JList) c;
Object vin = list.getSelectedValue();
if(vin instanceof VinAbstract)
{
System.out.println(vin);
// I created my Own transferable object for my custom object
return new TransferableVinAbstract((VinAbstract) vin);
}
return null;
}
@Override
public int getSourceActions(JComponent c) {
return COPY; // COPY MOVE COPY_OR_MOVE same problem :)
}
});
listPlantation.setModel(dlm);
如果我評論的SetTransferHandler部分,它的工作,而我有的只是我的對象的字符串表示。
當SetTransferHandler部件是「On」時,當我拖動我的對象時,在createTransferable >> System.out.println(vin)中打印出一些很好的東西。
最奇怪的事情是,我或多或少使用相同的代碼,爲JTree和它的工作,但它也不能與JTable的工作....
感謝您的反思呢!
也許[本教程](http://www.straub.as/java/clip-dnd/dnd.html)可能會有幫助。對我來說,我有一個類似的問題。 – 2017-03-13 08:34:53