|
Drag and Drop: New Data Transfer Capabilities in the JavaTM 2 Platform, Standard Edition (J2SETM), version 1.4(10) The following program demonstrates the ImageSelection class. There will be both a JLabel and JButton that uses the ImageSelection as its transfer handler. In the case of the label, three buttons will support different tasks: copying the image on the label to the clipboard, pasting an image on the clipboard to the label, and clearing the label. For the button, selection will act as a paste operation. Associating an ImageSelection as the transfer handler for a component isn't sufficient for the behavior part of the program to work. You must create an ActionListener to associate to the button and call the necessary TransferHandler method to move the data. As previously mentioned, eXPortToClipboard will copy the image off the component, and importData will paste it. Like with pasting strings, you still need to get the Transferable off the clipboard though. TransferHandler handler = label.getTransferHandler();// Copyhandler.eXPortToClipboard(label, clipboard,TransferHandler.COPY);// PasteTransferable clipData =clipboard.getContents(clipboard);if (clipData != null) {if (clipData.isDataFlavorSupported (DataFlavor.imageFlavor)) { handler.importData(label, clipData);}}To support pasting with the button component, you could do the same thing, but it isn't necessary. If the component that is to trigger the transfer is the source of the event, all you have to do is get the ActionListener right from the TransferHandler. There are three static methods for just sUCh an operation: getCopyAction, getCutAction, and getPasteAction. Here's all the code that is necessary to have button selection trigger pasting of the clipboard contents to the button, setting its icon label. JButton pasteB = new JButton("Paste");pasteB.setTransferHandler(new ImageSelection());pasteB.addActionListener(TransferHandler.getPasteAction());
|