David の低レベルのアプローチ (ラベルからドラッグするため) の高レベルの代替手段は、ビルド内のプロパティ転送を使用することです。transferHandler とエクスポートをトリガーする mouseListener を設定するだけでインストールされます。
MouseListener listener = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
JComponent c = (JComponent) e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
}
};
// a transferHandler configured to export the text property
TransferHandler handler = new TransferHandler("text");
JComponent labels = new JPanel();
for (int i = 0; i < 4; i++) {
JLabel label1 = new JLabel("item: " + i);
label1.addMouseListener(listener);
label1.setTransferHandler(handler);
labels.add(label1);
}
支払う代償は、TableTransferHandler での作業がわずかに増えることです。事前定義された stringFlavor に対してチェックするだけでなく、representationClass を String に対してチェックし、それも受け入れる必要があります。
public class TableHandlerExt extends TransferHandler {
/**
* Implemented to return true if the support can provide string values.
*/
@Override
public boolean canImport(TransferSupport support) {
if (!support.isDrop()) {
return false;
}
return isStringDataSupported(support);
}
/**
* Returns a boolean indicating whether or not the support can
* provide a string value. Checks for predefined DataFlavor.stringFlavor
* and flavors with a representationClass of String.
*/
protected boolean isStringDataSupported(TransferSupport support) {
if (support.isDataFlavorSupported(DataFlavor.stringFlavor)) return true;
DataFlavor[] flavors = support.getDataFlavors();
for (DataFlavor dataFlavor : flavors) {
if (dataFlavor.getRepresentationClass() == String.class) return true;
}
return false;
}
@Override
public boolean importData(TransferSupport support) {
if (!canImport(support)) {
return false;
}
String line;
try {
line = getStringData(support);
} catch (Exception e) {
e.printStackTrace();
return false;
}
JTable table = (JTable) support.getComponent();
JTable.DropLocation dl = (JTable.DropLocation) support.getDropLocation();
int column = dl.getColumn();
int row = dl.getRow();
if (!line.isEmpty()) {
// note: we need to use table api to access the table, as the
// row/column coordinates are view coordinates
table.setValueAt(line, row, column);
}
return true;
}
/**
* Returns the String provided by the support.
* Tries for predefined DataFlavor.stringFlavor
* and flavors with a representationClass of String.
*/
protected String getStringData(TransferSupport support)
throws UnsupportedFlavorException, IOException {
if (support.isDataFlavorSupported(DataFlavor.stringFlavor)) {
return (String) support.getTransferable().getTransferData(DataFlavor.stringFlavor);
}
DataFlavor[] flavors = support.getDataFlavors();
for (DataFlavor dataFlavor : flavors) {
if (dataFlavor.getRepresentationClass() == String.class) {
return (String) support.getTransferable().getTransferData(dataFlavor);
}
}
return "";
}
}