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);


}
}

ドロップ ターゲットである「テーブル」にマウス リスナーを追加して、マウスからどこにドロップしてもドロップ コンポーネントを受け入れることに問題があります。このコードでは、コンポーネントがドロップ ターゲットにドロップされると、常にデフォルトの位置に移動します。ドロップ ターゲットの位置をカスタマイズできません。誰かがこれで私を助けてください。前もって感謝します

4

1 に答える 1

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タグの説明にリンクされているオンラインチュートリアルの例、つまりドラッグアンドドロップの章を参照してください。上記のコードスニペットは、BasicDnDの例から抜粋したものです。

于 2012-07-08T08:46:31.033 に答える