【问题标题】:add mouse listeners to drop target添加鼠标侦听器以放置目标
【发布时间】:2012-07-08 07:53:58
【问题描述】:
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);


}
}

我在将鼠标侦听器添加到作为放置目标的“表”中时遇到问题,无论它从鼠标落下的任何地方都接受放置组件。在此代码中,当组件放入放置目标时,它始终会转到默认位置。我无法自定义放置目标的位置。请有人帮我解决这个问题。 在此先感谢

【问题讨论】:

  • 无关:组件的大小/定位是 LayoutManager 的专属任务,因此 setSize 从不使用(除了在空布局的恐怖场景中没有任何效果,不要-不要-不要 :)

标签: java swing jtable drag-and-drop


【解决方案1】:

那些听众太低级了。实现 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 上面的代码sn-p是从BasicDnD示例中c&p'ed的。

【讨论】:

    猜你喜欢
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 2012-08-01
    • 1970-01-01
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多