2012-07-08 85 views
2
DefaultTableModel modeltable = new DefaultTableModel(8,8); 

table = new JTable(modeltable); 
table.setBorder(BorderFactory.createLineBorder (Color.blue, 2)); 

int height = table.getRowHeight(); 
table.setRowHeight(height=50); 

table.setColumnSelectionAllowed(true); 
table.setDragEnabled(true); 

le1.setFillsViewportHeight(true); 

panel.add(table); 
panel.setSize(400,400); 

    DnDListener dndListener = new DnDListener(); 
    DragSource dragSource = new DragSource(); 
    DropTarget dropTarget1 = new DropTarget(table, dndListener); 

    DragGestureRecognizer dragRecognizer2 = dragSource. 
      createDefaultDragGestureRecognizer(option1, 
      DnDConstants.ACTION_COPY, dndListener); 
    DragGestureRecognizer dragRecognizer3 = dragSource. 
      createDefaultDragGestureRecognizer(option2, 
      DnDConstants.ACTION_COPY, dndListener); 


} 
} 

我有一個問題與添加鼠標偵聽爲「表」,它是放置目標,接受降低分量無論它從鼠標下降。在此代碼中,當組件進入放置目標時,它總是進入默認位置。我不能定製放置目標上的位置。請有人幫我解決這個問題。 在此先感謝添加鼠標偵聽下降目標

+0

不相關:組件的大小/位置是LayoutManager的獨佔任務,所以setSize是_never_使用(並且除了在空佈局的恐怖場景中沒有效果,_dont-dont-dont_ :) – kleopatra 2012-07-08 08:41:40

回答

5

那些聽衆太低級了。實現dnd的適當方法是實現一個自定義TransferHandler並將該自定義處理程序設置到您的表中。

public class MyTransferHandler extends TransferHandler { 

    public boolean canImport(TransferHandler.TransferSupport info) { 
     // we only import Strings 
     if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) { 
      return false; 
     } 

     JTable.DropLocation dl = (JTable.DropLocation)info.getDropLocation(); 
     // ... your code to decide whether the data can be dropped based on location 
    } 

    public boolean importData(TransferHandler.TransferSupport info) { 
     if (!info.isDrop()) { 
      return false; 
     } 

     // Check for String flavor 
     if (!info.isDataFlavorSupported(DataFlavor.stringFlavor)) { 
      displayDropLocation("Table doesn't accept a drop of this type."); 
      return false; 
     } 

     JTable.DropLocation dl = (JTable.DropLocation)info.getDropLocation(); 
     // ... your code to handle the drop 
    } 

} 

// usage 
myTable.setTransferHandler(new MyTransferHandler()); 

有關詳細信息,請參見在Swing標籤描述鏈接到在線教程的例子中,即chapter Drag and Drop上面的代碼段爲c &從BasicDnD示例p'ed。

相關問題