Java Reference
In-Depth Information
The parameter to the constructor represents the property of the component that you wish
to transfer. In other words, you identify the JavaBeans component property as the transferable
object for the drag-and-drop operation.
For instance, to transfer the text label of a JLabel , you would do the following:
JLabel label = new JLabel("Hello, World");
label.setTransferHandler(new TransferHandler("text"));
Since JLabel doesn't have a setDragEnabled() method, you must tell the component what
the start of the drag gesture is. Typically, this would be pressing the mouse button, so you
would also need to add a MouseListener to the button. When you tell the TransferHandler to
exportAsDrag() , that enables the dragging operation for the component.
MouseListener listener = new MouseAdapter() {
public void mousePressed(MouseEvent me) {
JComponent comp = (JComponent)me.getSource();
TransferHandler handler = comp.getTransferHandler();
handler.exportAsDrag(comp, me, TransferHandler.COPY);
}
};
button.addMouseListener(listener);
The default behavior when the drop gesture happens—releasing the mouse in this example—
would drop what was registered with the TransferHandler .
Listing 19-2 demonstrates a program that enables drag-and drop for the text in a JLabel .
Listing 19-2. Dragging Text from a JLabel
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DragLabel {
public static void main(String args[]) {
Runnable runner = new Runnable() {
public void run() {
JFrame frame = new JFrame("Drag Label");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Hello, World");
label.setTransferHandler(new TransferHandler("foreground"));
MouseListener listener = new MouseAdapter() {
public void mousePressed(MouseEvent me) {
JComponent comp = (JComponent)me.getSource();
TransferHandler handler = comp.getTransferHandler();
handler.exportAsDrag(comp, me, TransferHandler.COPY);
}
};
Search WWH ::




Custom Search