The example in this article describes how Java uses mouse drag and drop to exchange program data, which is the so-called mouse drag and drop function. The drag-and-drop function of the mouse is very commonly used in graphical systems. Java provides the java.awt.dnd and java.awt.datatransfer packages to support this function. This example demonstrates how to implement drag and drop in the program. When you click the mouse on the "Hello World!" label in the upper part of the window and drag it to the text box in the lower part of the window, "Hello World!" will be added to the text box. !" text; continue with the above process and the text will continue to be added.
The specific implementation ideas and methods of the program function are as follows: In the implementation of mouse drag and drop, the two most important concepts are drag source and drop target, namely drag source and drop target. The drag source and drop target are both associated with the visible component (how can you drag if it is not visible?!). The essence of drag-and-drop technology is to transfer the data on the drag-and-drop source component to the placement target component. Therefore, from a low-level perspective, drag-and-drop is very close to the clipboard technology in the above example.
Implementation of drag source: The drag source class must first create a DragGestureRecognizer instance, indicating that the class is a drag source component class or contains a drag source component. This can be achieved by calling the createDefaultDragGestureRecognizer() method of the DataSource object. The specific implementation is as follows:
int action = DnDConstants.ACTION_COPY_OR_MOVE; //Drag and drop type ds.createDefaultDragGestureRecognizer(this,action,this);
The above statement shows that the drag source component is an instance object of this class itself, the type of drag and drop to be completed is of type DnDConstants.ACTION_COPY_OR_MOVE, and the class that implements the DragGestureListener interface is this class. The drag source generally implements the DragGestureListener interface, which defines a dragGestureRecognized() method. When dragging starts, the DragGestureListener listens to the event, and then transfers to the dragGestureRecognized() method to process the event, such as sending the data of the drag source. Specific code:
public void dragGestureRecognized(DragGestureEvent dge) {//throw new java.lang.UnsupportedOperationException("Method dragGestureRecognized() not yet implemented."); try{Transferable tr = new StringSelection(this.getText()); //Transfer the label's Text as data, by Transferable Object packaging //Start dragging, set the cursor to DragSource.DefaultCopyNoDrop shape, the drag and drop data is a tr object, and DragSourceListener is this class dge.startDrag(DragSource.DefaultCopyNoDrop,tr,this);}catch(Exception err){err. printStackTrace();}}
The drag source must also implement the DragSourceListener interface, which defines event handling methods for each state related to drag and drop. Such as dragEnter, dragOver, dropActionChanged, dragExit and other methods. In this example, the dragEnter() method will be implemented to set the cursor shape during dragging, and other methods will be empty methods. The specific implementation code is as follows:
public void dragEnter(DragSourceDragEvent dsde) {//throw new java.lang.UnsupportedOperationException("Method dragEnter() not yet implemented.");DragSourceContext dsc = dsde.getDragSourceContext(); //Get the context reference of the drag source// Set the cursor shape when dragging int action = dsde.getDropAction();if ((action&DnDConstants.ACTION_COPY)!=0)dsc.setCursor(DragSource.DefaultCopyDrop);elsedsc.setCursor(DragSource.DefaultCopyNoDrop);}
Implementation of drop target: A DragTarget instance must be created first in the drop target class to indicate that this class is a drop target component class or contains a drop target component. The implementation is as follows:
new DropTarget(this.jTextField1,DnDConstants.ACTION_COPY_OR_MOVE,this);
The above statement shows that the drop target is this.jTextField1 object, the drag-and-drop operation is of type DnDConstants.ACTION_COPY_OR_MOVE, and the class that implements the DropTargetListener interface is this class. Corresponding to DrafSourceListener, the drop target or its class generally implements the DropTargetListener interface. This interface also defines many methods, such as dragEnter, dragOver, etc., for handling events when the drag-and-drop process enters different stages. This example only cares about the drop() method, which is the event processing when the mouse is released on the placement target component. It is generally used to process the passed data. For example, in this example, the passed text data will be displayed on the JTextField component. Others The method is an empty method, the specific code is as follows:
public void drop(DropTargetDropEvent dtde) {//throw new java.lang.UnsupportedOperationException("Method drop() not yet implemented.");try{Transferable tr = dtde.getTransferable(); //Get the passed data object/ /Process the data object and get the text information if (dtde.isDataFlavorSupported(DataFlavor.stringFlavor)){dtde.acceptDrop(dtde.getDropAction());String s = (String) tr.getTransferData(DataFlavor.stringFlavor);this.jTextField1.setText(this.jTextField1.getText() +s); //Display the text information passed from the drag source on the drop target dtde.dropComplete(true);}else{dtde.rejectDrop();}}catch(Exception err){err.printStackTrace();}}
Program code:
1. Create a new Project and name it JDragAndDropDemo.
2. Create a new Application and name it JDragAndDropDemo; name the main window MainFrame and title it JDragAndDropDemo.
3. Create a new Class, name it DragJLabel, and inherit the JLabel class.
4. Use wizards|implements interface to make DragJLabel class implement DragGestureListener and DragSourceListener interfaces.
5. Add a new attribute DragSource ds in class DragJLabel, the code is as follows:
class DragJLabel extends JLabel implements DragGestureListener, DragSourceListener {DragSource ds = DragSource.getDefaultDragSource(); //Create a DragSource instance...}
6. Write the constructor method of DragJLabel class.
public DragJLabel(String title,int alignment){super(title,alignment); //Use the parent class method int action = DnDConstants.ACTION_COPY_OR_MOVE;ds.createDefaultDragGestureRecognizer(this,action,this); //Create}
7. Implement the dragGestureRecognized() method in the DragJLabel class, wrap and send data.
public void dragGestureRecognized(DragGestureEvent dge) {//throw new java.lang.UnsupportedOperationException("Method dragGestureRecognized() not yet implemented.");try{Transferable tr = new StringSelection(this.getText());dge.startDrag(DragSource .DefaultCopyNoDrop,tr,this);}catch(Exception err){err.printStackTrace();}}
8. Implement the dragEnter() method in the DragJLabel class to set the shape of the cursor.
public void dragEnter(DragSourceDragEvent dsde) {//throw new java.lang.UnsupportedOperationException("Method dragEnter() not yet implemented.");DragSourceContext dsc = dsde.getDragSourceContext();int action = dsde.getDropAction();if ((action&DnDConstants.ACTION_COPY)!=0)dsc.setCursor(DragSource.DefaultCopyDrop);elsedsc.setCursor(DragSource.DefaultCopyNoDrop);}
9. Add a JTextField component in the lower part of the design window of the MainFrame class, and create a DragJLabel instance in the class. The specific code is as follows:
public class MainFrame extends JFrame implements DropTargetListener {private JPanel contentPane;private BorderLayout borderLayout1 = new BorderLayout();private JTextField jTextField1 = new JTextField();DragJLabel label = new DragJLabel("Hello World!",SwingConstants.CENTER);……}
10. Write the initialization method jbInit() of the MainFrame class, set the initial properties of the component, and create a new DropTarget instance. The code is as follows:
private void jbInit() throws Exception {//setIconImage(Toolkit.getDefaultToolkit().createImage(MainFrame.class.getResource("[Your Icon]")));contentPane = (JPanel) this.getContentPane();contentPane.setLayout (borderLayout1);this.setSize(new Dimension(410, 114));this.setTitle("JDragAndDropDemo");jTextField1.setFont(new java.awt.Font("Dialog", 0, 14));contentPane.add(jTextField1, BorderLayout.SOUTH);contentPane.add(this .label,BorderLayout.NORTH);new DropTarget(this.jTextField1,DnDConstants.ACTION_COPY_OR_MOVE,this);}
11. Use wizards|implements interface to make the MainFrame class implement the DropTargetListener interface.
12. Implement the method drop() inherited from the DropTargetListener interface to process the passed data. The specific code is as follows:
public void drop(DropTargetDropEvent dtde) {//throw new java.lang.UnsupportedOperationException("Method drop() not yet implemented.");try{Transferable tr = dtde.getTransferable();if (dtde.isDataFlavorSupported(DataFlavor.stringFlavor)){dtde.acceptDrop(dtde.getDropAction());String s = (String) tr.getTransferData(DataFlavor.stringFlavor);this.jTextField1.setText(this.jTextField1.getText()+s);dtde.dropComplete(true);}else{dtde.rejectDrop();}}catch(Exception err){ err.printStackTrace();}}