【问题标题】:Drag and drop from JList / JTable with Object使用 Object 从 JList / JTable 拖放
【发布时间】:2011-06-09 08:41:15
【问题描述】:

我在使用 Java 进行拖放时遇到了一些问题。

我认为这很简单,我只想允许将自定义对象从 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....

无论如何感谢您的反映!

【问题讨论】:

  • 也许this tutorial 会有所帮助。对我来说就是这样,我遇到了类似的问题。

标签: java swing drag-and-drop jlist


【解决方案1】:

我认为您需要编写一个自定义渲染器来处理您的对象。

【讨论】:

  • 感谢 Adeel 的回答。我将尝试制作自定义渲染器并发布反馈。 (但我仍然不明白为什么我必须为 JList 而不是 JTree #ItsMistery 这样做)
猜你喜欢
  • 1970-01-01
  • 2017-04-15
  • 2010-10-17
  • 2016-03-14
  • 2013-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多