问题
Currently I am having two tables say Table-A, Table-B. My task is to drag rows from Table-A to Table-B or drag rows from Table-B on to itself. Using TransferHandler I have achieved this task. But my problem is, I am not able to recognize from which table row was dragged to Table-B .. i.e, either from Table-A to Table-B or from Table-B on to itself. In exportData method of TransferHandler I am adding some additional data to one of the column. Basing on this, when I am importing data through importData method I am able to figure out from which table it came using that particular column to which I added data. I know this is not at all recommended .. so I need to know if there is a good way to approach this issue?
回答1:
You can create your own implementation of Transferable that will have a reference to the source component. Then in TransferHandler.importData() you can compare it with TransferSupport.getComponent() which is a destination component.
For example, here is a wrapper for a string that will be transferred:
public class DataWrapper {
String data;
Object source;
public DataWrapper(String data, Object source) {
super();
this.source = source;
this.data = data;
}
public String getData() {
return data;
}
public Object getSource() {
return source;
}
}
Here is a very basic Transferable implementation.
public class DataWrapperTransferable implements Transferable {
public static DataFlavor FLAVOR = new DataFlavor(DataWrapper.class,
"DataWrapper");
private DataFlavor flavors[];
private DataWrapper dataWrapper;
public DataWrapperTransferable(String data, Object source) {
dataWrapper = new DataWrapper(data, source);
flavors = new DataFlavor[] { FLAVOR };
}
@Override
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException {
if (flavor.equals(FLAVOR)) {
return dataWrapper;
} else {
throw new UnsupportedFlavorException(flavor);
}
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return flavors;
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(FLAVOR) || flavor.equals(DataFlavor.stringFlavor);
}
}
Then, in TransferHandler:
public boolean importData(TransferSupport support) {
DataWrapper dataWrapper = (DataWrapper) support
.getTransferable().getTransferData(
DataWrapperTransferable.FLAVOR);
if (dataWrapper.getSource() == support.getComponent()) {
//the originator and destination are the same
} else {
//drop from another component
}
//rest of the method
}
来源:https://stackoverflow.com/questions/13075943/jtable-drag-and-drop-using-transferhandler