2011-03-04 51 views
1

這是從OTN Discussions Forum轉發,因爲我沒有得到答案。DropDemo中的ListTransferHandler有一個bug

在Java中,我想在包含字符串的JList中啓用拖放操作。爲此,我使用了Oracle的DropDemo中使用的ListTransferHandler.java。不幸的是,這個ListTransferHandler.java有一個錯誤。

要重現錯誤的ListTransferHandler.java我做了以下內容:

取而代之:

  • 清單項目1
  • 貨品0

我得到這個:

  • 清單項目1
  • 清單項目1

這顯然是不預期的結果。

Netbeans的輸出窗口沒有顯示任何錯誤消息。我試圖自己發現錯誤,但沒有成功。

所以我錯過了在JList中啓用DnD的意義?我不需要自己實現一個ListTransferHandler嗎?

有沒有人爲我工作ListTransferHandler請或知道如何解決在演示中使用的一個?

感謝和問候, 庫爾特

回答

0

這肯定是一個錯誤。看看ListTransferHandler#清理方法。其目標是從列表中刪除以前選擇的項目。指數修正刪除之前執行:

 if (addCount > 0) { 
      for (int i = 0; i < indices.length; i++) { 
       if (indices[i] > addIndex) { 
        indices[i] += addCount; 
       } 
      } 
     } 

不知何故,方法ListTransferHandler#importString初始化addCount不會被調用,因此,修正是永遠做不完的。

作爲一種解決辦法,你可以自己初始化:

 int addCount = indices.length; 

這將解決INSERT放置模式。

UPD:

只注意到其它降模式太碎。所以,最後的修復(似乎是這樣):

public class ListTransferHandler extends TransferHandler { 
    private boolean insert; 
    //........ 
    public boolean importData(TransferHandler.TransferSupport info) { 
     //...... 
     insert = dl.isInsert(); 
     //...... 

    protected void exportDone(JComponent c, Transferable data, int action) { 
     cleanup(c, insert && action == TransferHandler.MOVE); 
    } 

    protected void cleanup(JComponent c, boolean remove) { 
     if (remove && indices != null) { 
      int addCount = indices.length; 
     //..... 

} 

此外,應刪除所有未使用的字段和方法。

+0

對於INSERT,布爾刪除應該是假的,但它是真的。 – 2011-03-04 19:49:26

+0

_ @ StackOverflowException_只要'remove =(action == TransferHandler.MOVE)'實際插入僅在用戶持有_Ctrl_時執行。 – n0weak 2011-03-04 20:13:06

0

@ n0weak感謝您的回答我可以修復ListTransferHandler以滿足我的需求(多選仍然被打破,而且我還沒有測試其他模式而不是INSERT)。

我發現有必要記住addIndex以及上面的解決方案。這裏是我使用的代碼更改:

public class ListTransferHandler extends TransferHandler { 
    // ... 
    private boolean insert; 
    // ... 

public boolean importData(TransferHandler.TransferSupport info) { 
     // ...    
     // method local variables were mistakenly used 
     insert = dl.isInsert(); 
     addIndex = dl.getIndex(); // also replace index with addIndex a few lines below 
     addCount = indices.length; 
     // ... 

protected void exportDone(JComponent c, Transferable data, int action) { 
     cleanup(c, insert && action == TransferHandler.MOVE); 
    } 

/* protected void importString(JComponent c, String str) {...} 
    This method is never called */