📄 intro.html
字号:
serialization, so the class you use to transfer the datamust implement the <code>Serializable</code> interface,as must anything that is serialized with it. If not everything is <code>Serializable</code>, you'll see a<code>NotSerializableException</code> during drop or copy to the clipboard.<p>Note that creating a data flavor using the<code>DataFlavor(Class, String)</code> constructorallows you to transfer data between applications,including native applications.If you want to create a data flavor that transfers dataonly within an application, you use <code>javaJVMLocalObjectMimeType</code> and the<code>DataFlavor(String)</code> constructor. For example, to specify a data flavor that transfers color from a<code>JColorChooser</code>, you could use this code:<blockquote><pre>String colorType = DataFlavor.javaJVMLocalObjectMimeType + ";class=java.awt.Color";DataFlavor colorFlavor = new DataFlavor(colorType);</pre></blockquote><p>To create a data flavor for an <code>ArrayList</code>:<blockquote><pre>new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + ";class=java.util.ArrayList");</pre></blockquote><p>To transfer the data as an integer array you would use:<blockquote><pre>new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + ";class=\"" + int[].class.getName() + "\"");</pre></blockquote><p>You'll see that a MIME type containing special characters,(such as <b>[</b> and <b>;</b>),must have those characters enclosed in quotes.<p>Finally, a <code>Transferable</code> can be implemented tosupport multiple flavors. For example, you can use both localand serialization flavors together, or you can use two forms of thesame data, such as the <code>ArrayList</code> and integer arrayflavors, together, or you can createa <code>TransferHandler</code> that accepts different types of data, such as color and text,as you will later see. When you create the array of<code>DataFlavors</code> to be returned from the<code>Transferable</code>'s<code>getTransferDataFlavors</code> method,the flavors should be inserted in preferred order,with the most preferred appearing at element 0 of the array.Generally the preferred order is from the richest or mostcomplex form of the data down to the simplest — the formmost likely to be understood by other objects.<p>See the<a class="OutsideLink" target="_blank" href="http://java.sun.com/j2se/1.4.2/docs/guide/swing/1.4/dnd.html#DefaultTransferHandlerSupport">Components That Support DnD</a> table in the release notes for your particular J2SE releasefor further details of which data types each component importsand exports.</blockquote> <a name=customImport><h2>Importing a New Flavor: Color</h2></a><blockquote><p>The only Swing component that can, by default, import or exportcolor is <code>JColorChooser</code>. We prevously described howyou can create a transfer handler that will transfer data asspecified by a named property. While this is easy to do,it has limited functionality. For example, if you specifythe "foreground" property, a drop would only change the colorof the text. It wouldn't change the background color.And if your component drags and drops text by default, replacingthe transfer handler in this mannercauses the component to lose this default ability.<p>To solve this problem you need towrite a custom <code>TransferHandler</code>. We have provided an exampleof how to create a custom transfer handler that can be installedon a component so that it can accept color on a drop.<code>DragColorDemo</code> specifically shows how you can dropa color onto the foreground or background of a button or label.<p><center><IMG SRC="../../figures/uiswing/dnd/DragColorDemo.png" WIDTH="477" HEIGHT="544" ALIGN="BOTTOM" ALT="The DragColorDemo example"></center></p><blockquote><hr><strong>Try this:</strong> <ol><li> <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/misc/examples/DragColorDemo.jnlp">Run DragColorDemo</a> using <a href=http://java.sun.com/products/javawebstart> Java Web Start</a>. Or, to compile and run the example yourself, consult the <a href="examples/index.html#DragColorDemo">example index</a>.<li> Select a color from the palette. The selected color appears in the Preview panel.<li> Press and hold the mouse button while the cursor is over the Preview panel and begin to drag.<li> Drop the color onto the label and see the text change color.<li> Select another color. Drop onto a button. The color of the button text changes.<li> Click the "Change the foreground color" check box so that it is no longer checked.<li> Drop another color onto a button or the label. The background color changes.</ol><hr></blockquote><p>The example's main class can be found in<a href=examples/DragColorDemo.java><code>DragColorDemo.java</code></a>. The custom transfer handleris defined in <a href=examples/ColorTransferHandler.java><code>ColorTransferHandler.java</code></a>.In this example, we are only implementing import functionalityand therefore only need to implement the methods<code>canImport</code> and <code>importData</code>.A single instance of the <code>ColorTransferHandler</code>is created and shared by all nine buttons and the label.Here is a snippet of code where the transfer handler iscreated and installed on the buttons:<blockquote><pre>colorHandler = new ColorTransferHandler();...for (int i = 0; i < 9; i++) { JButton tmp = new JButton("Button "+i); tmp.setTransferHandler(colorHandler); ....}</pre></blockquote>Here is the code for <code>ColorTransferHandler</code>:<blockquote><pre>class ColorTransferHandler extends TransferHandler { //The data type exported from JColorChooser. String mimeType = DataFlavor.javaJVMLocalObjectMimeType + ";class=java.awt.Color"; DataFlavor colorFlavor; private boolean changesForegroundColor = true; ColorTransferHandler() { //Try to create a DataFlavor for color. try { colorFlavor = new DataFlavor(mimeType); } catch (ClassNotFoundException e) { } } /** * Overridden to import a Color if it is available. * getChangesForegroundColor is used to determine whether * the foreground or the background color is changed. */ public boolean importData(JComponent c, Transferable t) { if (hasColorFlavor(t.getTransferDataFlavors())) { try { Color col = (Color)t.getTransferData(colorFlavor); if (getChangesForegroundColor()) { c.setForeground(col); } else { c.setBackground(col); } return true; } catch (UnsupportedFlavorException ufe) { } catch (IOException ioe) { } } return false; } /** * Does the flavor list have a Color flavor? */ protected boolean hasColorFlavor(DataFlavor[] flavors) { if (colorFlavor == null) { return false; } for (int i = 0; i < flavors.length; i++) { if (colorFlavor.equals(flavors[i])) { return true; } } return false; } /** * Overridden to include a check for a color flavor. */ public boolean canImport(JComponent c, DataFlavor[] flavors) { return hasColorFlavor(flavors); } protected void setChangesForegroundColor(boolean flag) { changesForegroundColor = flag; } protected boolean getChangesForegroundColor() { return changesForegroundColor; }}</pre></blockquote><p>The <code>ColorTransferHandler</code> is implemented tosupport <code>JavaJVMlocalObjectMimeType</code> with therepresentation class <code>class=java.awt.Color</code>, whichis the mechanism <code>JColorChooser</code> uses to export color.For a discussion of how data is specified to the transfermechanism, see the previous section<a href=#dataFormat>Specifying the Data Format</a>.</blockquote><a name=replacingSupport><h2>Replacing Default Support: Color and Text</h2></a><blockquote>The <code>DragColorDemo</code> example shown in <a href=#customImport>Importing a New Flavor: Color</a>replaces the component's current transfer handler.When <code>DragColorDemo</code> installsthe <code>ColorTransferHandler</code> on its components,it clobbers any pre-existing transfer handler.This is not so much a problem with buttons or labels, whichdon't have any predefined data to transfer, but it can bea problem when you want to add the ability to import/exportcolor on top of a component that already imports/exportsother data, such as text.As discussed in <a href=#customGotcha>Introduction to Data TransferSupport</a>, if you install a custom transfer handleronto a component, such as <code>JTextField</code>,that has a Swing-provided transfer handler, you would needto re-implement the Swing support.We have provided a version of <code>DragColorDemo</code>, called<code>DragColorTextFieldDemo</code>, that creates a transferhandler that accepts color and also re-implements the clobberedsupport for text.<p><center><IMG SRC="../../figures/uiswing/dnd/DragColorTextFieldDemo.png" WIDTH="477" HEIGHT="499" ALIGN="BOTTOM" ALT="The DragColorTextFieldDemo example"></center></p><blockquote><hr><strong>Try this:</strong> <ol><li> <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/misc/examples/DragColorTextFieldDemo.jnlp">Run DragColorTextFieldDemo</a> using <a href=http://java.sun.com/products/javawebstart> Java Web Start</a>. Or, to compile and run the example yourself, consult the <a href="examples/index.html#DragColorTextFieldDemo">example index</a>.<li> Select a color from the palette. Drag the color from the Preview panel to one of the text fields. Each text field can have its own color.<li> Select some text and drag to move to another text field.<li> Hold down the Control key while dragging to copy the text to another text field.<li> Cut some text either using the menu item or the key binding: Control-X.<li> Select a location to paste the text and paste, either using the menu item or the key binding: Control-V.<li> Copy some text using Control-C and paste it with Control-V.<li> Select some text, drag to a native application, such as a text editor, and drop. The text is inserted.<li> Select some text in the native text editor, drag to the text area and drop. The text is inserted.</ol><hr></blockquote><p>This transfer handler descends from<code>ColorTransferHandler</code> which was used in the<code>DragColorDemo</code> example. Since<code>ColorAndTextTransferHandler</code>must export data, it implements <code>createTransferable</code>,<code>getSourceActions</code>, and <code>exportDone</code>(in addition to the two methods it provides for import support).The code is too long to include here, but you can find the main class's source code in <a href=examples/DragColorTextFieldDemo.java><code>DragColorTextFieldDemo.java</code></a>.The custom transfer handler is in<a href=examples/ColorAndTextTransferHandler.java><code>ColorAndTextTransferHandler.java</code></a>.</blockquote><a name=importFiles><h2>Importing a New Flavor: Files</h2></a><blockquote><p>The <code>JFileChooser</code> exportsthe <code>javaFileListFlavor</code> — a<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/util/List.html"><code>List</code></a> of <a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/io/File.html"><code>File</code></a> objects discussed in <a href=#dataFormat>Specifyingthe Data Format</a>. The file chooser also exportsits filenames as a list of <code>String</code>s —both in <code>text/plain</code> and <code>text/html</code>formats. For example, dragging a file from a drag-enabledfile chooser and dropping it on a <code>JTextArea</code>causes the file name to be inserted into the text area,but not the contents of the file.However, a custom transfer handler that knows about<code>javaFileListFlavor</code> can be installed toaccept the file list provided by a file chooser, openthe file, read the contents, and display the contents of thefile in the text area.We have provided an example that does this.Note that because this example reads files fromyour local file system, launching the demo viaJava Web Start will bring up a warning panel requiringpermission before executing the application. If youprefer, you can instead download the applicationand run it locally.<p><center><IMG SRC="../../figures/uiswing/dnd/DragFileDemo.png" WIDTH="538" HEIGHT="393" ALIGN="BOTTOM" ALT="The DragFileDemo example"></center></p><blockquote><hr><strong>Try this:</strong> <ol><li> <a href="http://java.sun.com/docs/books/tutorialJWS/uiswing/misc/examples/DragFileDemo.jnlp">Run DragFileDemo</a> using <a href=http://java.sun.com/products/javawebstart> Java Web Start</a>. Or, to compile and run the example yo
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -