下面列出了怎么用javax.swing.TransferHandler的API类实例代码及写法,或者点击链接到github查看源代码。
public DraggableButton(final Action action) {
super(action);
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(final MouseEvent event) {
getTransferHandler().exportAsDrag(DraggableButton.this, event, TransferHandler.COPY);
}
});
t = new TransferHandler("graph") {
@Override
public Transferable createTransferable(final JComponent c) {
return new StringSelection("graphSelection");
}
};
setTransferHandler(t);
source = new DragSource();
source.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY, this);
}
/**
*
*/
public void exportDone(JComponent c, Transferable data, int action)
{
initialImportCount = 1;
if (c instanceof mxGraphComponent
&& data instanceof mxGraphTransferable)
{
// Requires that the graph handler resets the location to null if the drag leaves the
// component. This is the condition to identify a cross-component move.
boolean isLocalDrop = location != null;
if (action == TransferHandler.MOVE && !isLocalDrop)
{
removeCells((mxGraphComponent) c, originalCells);
initialImportCount = 0;
}
}
originalCells = null;
location = null;
offset = null;
}
@SuppressWarnings("unchecked")
@Override
public boolean importData(TransferHandler.TransferSupport info) {
if (!info.isDrop())
return false;
Transferable t = info.getTransferable();
List<File> data = null;
try {
data = (List<File>) t.getTransferData(DataFlavor.javaFileListFlavor);
} catch (Exception e) {
return false;
}
user.preLoadJars(id);
for (File jar : data) {
if (jar.getName().toLowerCase().endsWith(".jar")) {
user.onJarLoad(id, jar);
break;
}
}
return true;
}
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
if (!support.isDrop()) {
return false;
}
if (!support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
return false;
}
boolean actionSupported = (MOVE & support.getSourceDropActions()) == MOVE;
if (!actionSupported) {
return false;
}
support.setDropAction(MOVE);
return true;
}
@Override
public void setDocument(Document doc) {
super.setDocument(doc);
// Setting DelegatingTransferHandler, where CallbackTransferable will
// be handled in importData method.
// For more details, please refer issue #53439
if (doc != null){
TransferHandler thn = getTransferHandler();
if( !(thn instanceof DelegatingTransferHandler) ) {
DelegatingTransferHandler dth = new DelegatingTransferHandler(thn);
setTransferHandler(dth);
}
DropTarget currDt = getDropTarget();
if( !(currDt instanceof DelegatingDropTarget ) ) {
DropTarget dt = new DelegatingDropTarget( currDt );
setDropTarget( dt );
}
}
}
/**
* Creates new form TreeGuiView
*/
public TreeGuiView() {
initComponents();
TreeTrasferHandling trasferHandling = new TreeTrasferHandling();
this.jTree2.setTransferHandler(trasferHandling);
CommandProcessor.getInstance().getObservable().addObserver(this);
ActionMap map = this.getActionMap();
map.put(TransferHandler.getCopyAction().getValue(javax.swing.Action.NAME),
TransferHandler.getCopyAction());
map.put(TransferHandler.getPasteAction().getValue(javax.swing.Action.NAME),
TransferHandler.getPasteAction());
map.put(TransferHandler.getCutAction().getValue(javax.swing.Action.NAME),
TransferHandler.getCutAction());
}
public void dragEnter(DropTargetDragEvent event) {
DataFlavor[] dataFlavors = event.getCurrentDataFlavors();
JComponent c = (JComponent) event.getDropTargetContext().getComponent();
TransferHandler transferHandler = c.getTransferHandler();
if ((transferHandler != null) && transferHandler.canImport(c, dataFlavors)) {
canImport = true;
} else {
canImport = false;
}
int dropAction = event.getDropAction();
if (canImport && actionSupported(dropAction)) {
event.acceptDrag(dropAction);
} else {
event.rejectDrag();
}
}
private Boolean reorderProjects(TransferHandler.TransferSupport support) {
JList list = (JList) support.getComponent();
try {
int[] selectedIndices = (int[]) support.getTransferable().getTransferData(INDICES);
DefaultListModel model = (DefaultListModel) list.getModel();
JList.DropLocation dl = (JList.DropLocation) support.getDropLocation();
if (dl.getIndex() != -1) {
for (int selectedIndex : selectedIndices) {
Object value = model.get(selectedIndex);
model.removeElement(value);
model.add(dl.getIndex(), value);
}
return true;
} else {
LOG.warning("Invalid Drop Location");
}
} catch (UnsupportedFlavorException | IOException ex) {
LOG.log(Level.SEVERE, ex.getMessage(), ex);
}
return false;
}
private void setCCP() {
TransferActionListener actionListener = new TransferActionListener();
cut = new JMenuItem("Cut");
cut.setActionCommand((String) TransferHandler.getCutAction().getValue(Action.NAME));
cut.addActionListener(actionListener);
cut.setAccelerator(Keystroke.CUT);
cut.setMnemonic(KeyEvent.VK_T);
add(cut);
copy = new JMenuItem("Copy");
copy.setActionCommand((String) TransferHandler.getCopyAction().getValue(Action.NAME));
copy.addActionListener(actionListener);
copy.setAccelerator(Keystroke.COPY);
copy.setMnemonic(KeyEvent.VK_C);
add(copy);
paste = new JMenuItem("Paste");
paste.setActionCommand((String) TransferHandler.getPasteAction().getValue(Action.NAME));
paste.addActionListener(actionListener);
paste.setAccelerator(Keystroke.PASTE);
paste.setMnemonic(KeyEvent.VK_P);
add(paste);
}
private void setCCP() {
TransferActionListener actionListener = new TransferActionListener();
cut = new JMenuItem("Cut");
cut.setActionCommand((String) TransferHandler.getCutAction().getValue(Action.NAME));
cut.addActionListener(actionListener);
cut.setAccelerator(Keystroke.CUT);
cut.setMnemonic(KeyEvent.VK_T);
add(cut);
copy = new JMenuItem("Copy");
copy.setActionCommand((String) TransferHandler.getCopyAction().getValue(Action.NAME));
copy.addActionListener(actionListener);
copy.setAccelerator(Keystroke.COPY);
copy.setMnemonic(KeyEvent.VK_C);
add(copy);
paste = new JMenuItem("Paste");
paste.setActionCommand((String) TransferHandler.getPasteAction().getValue(Action.NAME));
paste.addActionListener(actionListener);
paste.setAccelerator(Keystroke.PASTE);
paste.setMnemonic(KeyEvent.VK_P);
add(paste);
}
@Override
public boolean importData(TransferHandler.TransferSupport support) {
if (!canImport(support)) {
return false;
}
JTable.DropLocation dl = (JTable.DropLocation) support.getDropLocation();
JTable table = (JTable) support.getComponent();
int row = dl.getRow();
int tcRow = dl.getColumn() - 1;
if (row == -1) {
return false;
}
Scenario scenario = (Scenario) table.getModel();
TestCase testCase = scenario.getTestCaseByName(
table.getValueAt(row, 0).toString());
if (dropObject instanceof TestCaseDnD) {
putReusables(testCase, tcRow);
} else {
return false;
}
return super.importData(support);
}
@Override
public boolean canImport(final TransferHandler.TransferSupport support) {
if (!support.isDataFlavorSupported(DataFlavor.stringFlavor)) {
return false;
}
JList.DropLocation dl = (JList.DropLocation) support.getDropLocation();
return dl.getIndex() != -1;
}
/**
* Display messages.
*
* @param destinationTreeNode the destination tree node
* @param transferredData the transferred data
* @param action the action
*/
public static void displayMessages(
NodeInterface destinationTreeNode, TransferredData transferredData, int action) {
if ((destinationTreeNode == null) || (transferredData == null)) {
return;
}
String actionString = "???";
if (action == TransferHandler.MOVE) {
actionString = "Moved";
} else if (action == TransferHandler.COPY) {
actionString = "Copied";
}
String destinationString =
destinationTreeNode.getHandler().getDestinationText(destinationTreeNode);
for (int index = 0; index < transferredData.getDataListSize(); index++) {
NodeInterface nodeToTransfer =
(NodeInterface) transferredData.getTreePath(index).getLastPathComponent();
SelectedFiles selectedFiles =
nodeToTransfer.getHandler().getSLDContents(nodeToTransfer);
for (SLDDataInterface sldData : selectedFiles.getSldData()) {
ConsoleManager.getInstance()
.information(
DataFlavourManager.class,
String.format(
"%s %s -> %s",
actionString, sldData.getLayerName(), destinationString));
}
}
}
@Override
public boolean canImport(TransferHandler.TransferSupport support)
{
if (!support.isDataFlavorSupported(DataFlavor.javaFileListFlavor) &&
!support.isDataFlavorSupported(URL_FLAVOR))
{
return false;
}
support.setDropAction(COPY);
return true;
}
/**
*
*/
protected MouseEvent createEvent(DropTargetEvent e)
{
JComponent component = getDropTarget(e);
Point location = null;
int action = 0;
if (e instanceof DropTargetDropEvent)
{
location = ((DropTargetDropEvent) e).getLocation();
action = ((DropTargetDropEvent) e).getDropAction();
}
else if (e instanceof DropTargetDragEvent)
{
location = ((DropTargetDragEvent) e).getLocation();
action = ((DropTargetDragEvent) e).getDropAction();
}
if (location != null)
{
location = convertPoint(location);
Rectangle r = graphComponent.getViewport().getViewRect();
location.translate(r.x, r.y);
}
// LATER: Fetch state of modifier keys from event or via global
// key listener using Toolkit.getDefaultToolkit().addAWTEventListener(
// new AWTEventListener() {...}, AWTEvent.KEY_EVENT_MASK). Problem
// is the event does not contain the modifier keys and the global
// handler is not called during drag and drop.
int mod = (action == TransferHandler.COPY) ? InputEvent.CTRL_MASK : 0;
return new MouseEvent(component, 0, System.currentTimeMillis(), mod,
location.x, location.y, 1, false, MouseEvent.BUTTON1);
}
@Override
public int getSourceActions(JComponent c) {
logger.debug("getSourceActions " + c.getClass().getCanonicalName());
TransferHandler th = getTransferHandlerForSelection(c);
if (th != null) {
return th.getSourceActions(c);
}
return TransferHandler.NONE;
}
@SuppressWarnings("unchecked")
@Override
public boolean importData(TransferSupport info) {
TransferHandler.DropLocation dropLocation = info.getDropLocation();
if (!canImport(info) || !(dropLocation instanceof JList.DropLocation)) {
return false;
}
JList.DropLocation dl = (JList.DropLocation) dropLocation;
JList target = (JList) info.getComponent();
DefaultListModel listModel = (DefaultListModel) target.getModel();
int max = listModel.getSize();
int index = dl.getIndex();
index = index < 0 ? max : index;
// make sure to append at the end if index > size
index = Math.min(index, max);
addIndex = index;
try {
Object[] values = (Object[]) info.getTransferable().getTransferData(localObjectFlavor);
for (Object value : values) {
int idx = index++;
listModel.add(idx, value);
target.addSelectionInterval(idx, idx);
}
addCount = values.length;
return true;
} catch (UnsupportedFlavorException | IOException e) {
// should never happen, log anyway to be safe
LogService.getRoot().log(Level.WARNING, "com.rapidminer.gui.tools.dnd.ExtendedJListTransferHandler.unexpected_error", e);
}
return false;
}
@Override
public void setTransferHandler(TransferHandler newHandler) {
TransferHandler oldHandler = (TransferHandler)
getClientProperty(AWTAccessor.getClientPropertyKeyAccessor()
.getJComponent_TRANSFER_HANDLER());
putClientProperty(AWTAccessor.getClientPropertyKeyAccessor()
.getJComponent_TRANSFER_HANDLER(),
newHandler);
firePropertyChange("transferHandler", oldHandler, newHandler);
}
@Override
public void setTransferHandler(TransferHandler newHandler) {
TransferHandler oldHandler = (TransferHandler)
getClientProperty(AWTAccessor.getClientPropertyKeyAccessor()
.getJComponent_TRANSFER_HANDLER());
putClientProperty(AWTAccessor.getClientPropertyKeyAccessor()
.getJComponent_TRANSFER_HANDLER(),
newHandler);
firePropertyChange("transferHandler", oldHandler, newHandler);
}
@Override
public void setTransferHandler(TransferHandler newHandler) {
TransferHandler oldHandler = (TransferHandler)
getClientProperty(AWTAccessor.getClientPropertyKeyAccessor()
.getJComponent_TRANSFER_HANDLER());
putClientProperty(AWTAccessor.getClientPropertyKeyAccessor()
.getJComponent_TRANSFER_HANDLER(),
newHandler);
firePropertyChange("transferHandler", oldHandler, newHandler);
}
@Override
public void setTransferHandler(TransferHandler newHandler) {
TransferHandler oldHandler = (TransferHandler)
getClientProperty(AWTAccessor.getClientPropertyKeyAccessor()
.getJComponent_TRANSFER_HANDLER());
putClientProperty(AWTAccessor.getClientPropertyKeyAccessor()
.getJComponent_TRANSFER_HANDLER(),
newHandler);
firePropertyChange("transferHandler", oldHandler, newHandler);
}
@Override
public void setTransferHandler(TransferHandler newHandler) {
TransferHandler oldHandler = (TransferHandler)
getClientProperty(AWTAccessor.getClientPropertyKeyAccessor()
.getJComponent_TRANSFER_HANDLER());
putClientProperty(AWTAccessor.getClientPropertyKeyAccessor()
.getJComponent_TRANSFER_HANDLER(),
newHandler);
firePropertyChange("transferHandler", oldHandler, newHandler);
}
private void init() {
transferHandler = new TransferHandler() {
@Override
protected Transferable createTransferable(JComponent c) {
return new DnDToggleButton(getText(), getIcon());
}
};
setTransferHandler(transferHandler);
source = new DragSource();
source.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY, this);
}
protected void inMiddleOfSettingUpTheManager() {
assertNotNull("There is a manager already", System.getSecurityManager());
// do some strange tricks to initialize the system
field = new javax.swing.JTextField ();
TransferHandler.getCopyAction();
TransferHandler.getCutAction();
TransferHandler.getPasteAction();
}
@Override
public boolean canImport(TransferHandler.TransferSupport info) {
if (!info.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
return false;
}
return true;
}
@Override
public void setTransferHandler(TransferHandler newHandler) {
TransferHandler oldHandler = (TransferHandler)
getClientProperty(AWTAccessor.getClientPropertyKeyAccessor()
.getJComponent_TRANSFER_HANDLER());
putClientProperty(AWTAccessor.getClientPropertyKeyAccessor()
.getJComponent_TRANSFER_HANDLER(),
newHandler);
firePropertyChange("transferHandler", oldHandler, newHandler);
}
@Override
public void setTransferHandler(TransferHandler newHandler) {
TransferHandler oldHandler = (TransferHandler)
getClientProperty(AWTAccessor.getClientPropertyKeyAccessor()
.getJComponent_TRANSFER_HANDLER());
putClientProperty(AWTAccessor.getClientPropertyKeyAccessor()
.getJComponent_TRANSFER_HANDLER(),
newHandler);
firePropertyChange("transferHandler", oldHandler, newHandler);
}
@Override
public boolean canImport(TransferHandler.TransferSupport support) {
logger.debug("canImport " + support.getComponent().getClass().getCanonicalName());
TransferHandler th = getTransferHandlerForSelection(support.getComponent());
if (th != null) {
return th.canImport(support);
}
return false;
}
@Override
public boolean importData(TransferHandler.TransferSupport info) {
JTable target = (JTable) info.getComponent();
JTable.DropLocation dl = (JTable.DropLocation) info.getDropLocation();
int index = dl.getRow();
int max = table.getModel().getRowCount();
if (index < 0 || index > max) {
index = max;
}
target.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
try {
Integer rowFrom = (Integer) info.getTransferable().getTransferData(localObjectFlavor);
if (rowFrom != -1 && rowFrom != index) {
Vector<Object> rowData = (Vector) getTableModel().getDataVector().get(rowFrom);
getTableModel().removeRow(rowFrom);
getTableModel().insertRow(index, rowData);
if (index > rowFrom) {
index--;
}
target.getSelectionModel().addSelectionInterval(index, index);
return true;
}
} catch (UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}
return false;
}
public final void startDrag(MouseEvent e) {
if(enable){
if (!(this.getSelected() instanceof GScreen) && !(this.getSelected() instanceof GLayer)) {
JPanel c = (JPanel) e.getComponent();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.MOVE);
this.niftyView.getDDManager().startDrag(this.getSelected());
}
}
}