|
Drag and Drop: New Data Transfer Capabilities in the JavaTM 2 Platform, Standard Edition (J2SETM), version 1.4(13) Here's a simple program to demonstrate how easy drag-and-drop operations are with the new release of J2SE. It provides a JTextField and a JTree, both of which have drag enabled. The JTextField also supports drop operations, so you can drag something from the tree to the text field, but you must do additional work to enable drop on a JTree component. import Java.awt.*;import Java.awt.datatransfer.*;import Javax.swing.*;public class DragOne {public static void main(String args[]) { JFrame frame = new JFrame("First Drag"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contentPane = frame.getContentPane(); JTree tree = new JTree(); JScrollPane pane = new JScrollPane(tree); contentPane.add(pane, BorderLayout.CENTER); tree.setDragEnabled(true); JTextField tf = new JTextField(); tf.setDragEnabled(true); contentPane.add(tf, BorderLayout.NORTH); frame.setSize(300, 300); frame.show();}}In order to drag a node from the tree, you must select the icon associated with the specific node. Also, be sure to try to drag multiple selected nodes from the JTree component. This will drag the entries as an ordered HTML list. While some components have built-in support for drag-and-drop operations, not all do. For instance, if you wanted to support dragging the image on a JLabel, you would have to initiate the drag operation yourself when the mouse was pressed over the component. MouseListener mouseListener = new MouseAdapter() {public void mousePressed(MouseEvent e) { JComponent comp = (JComponent)e.getSource(); TransferHandler handler = comp.getTransferHandler(); handler.eXPortAsDrag(comp, e, TransferHandler.COPY);}};label.addMouseListener(mouseListener);
|