Java Reference
In-Depth Information
label.addMouseListener(listener);
frame.add(label, BorderLayout.SOUTH);
JTextField text = new JTextField();
frame.add(text, BorderLayout.NORTH);
frame.setSize(300, 150);
frame.setVisible(true);
}
};
EventQueue.invokeLater(runner);
}
}
Figure 19-2 shows this program during the drag operation. Notice how the cursor changes
to indicate the operation.
Figure 19-2. Dragging text from a JLabel to a JTextField
If instead of dragging the text of the JLabel , you wanted to drag the foreground color, the
only change to the program would be to the setTransferHandler() line:
label.setTransferHandler(new TransferHandler("foreground"));
Then, assuming you had some place to drop the color, as in the program in Listing 19-1,
you could drag the foreground color out of the label to the JColorChooser , and then drop the
color out of the JColorChooser into the JLabel . Since the TransferHandler is registered for a
specific property of the component, there is no explicit code necessary to handle dropping.
Instead, the setter method for the property passed into the handler constructor is notified of
the change.
Drag-and-Drop Support for Images
If you wish to transfer something other than a simple property, you need to create an implementa-
tion of the Transferable interface, found in the java.awt.datatransfer package. Transferable
implementations are typically meant for transfers through the clipboard, but by having your
implementation be a TransferHandler subclass, you can use it to drag-and-drop the object.
The three methods of the Transferable interface are shown here:
 
Search WWH ::




Custom Search