Java implementation of the mouse drag and drop function method

  • 2020-04-01 03:25:03
  • OfStack

This article illustrates how Java USES mouse drag and drop to exchange program data. The drag-and-drop functionality of the mouse is very common in graphical systems, and Java provides the java.awt.dnd and java.awt.datatransfer packages to support it. This example demonstrates how to implement a drag-and-drop method in a program, as shown in the "Hello World!" section at the top of the window. Click the mouse on the TAB and drag it to the text box at the bottom of the window to let go, adding "Hello World!" to the text box. Text; Continuing with the process, the text will continue to be added.

The specific realization ideas and methods of the program function are as follows: The two most important concepts in the implementation of mouse drag and drop are drag source and drop target, namely drag source and drop target. Both the drag-and-drop source and the drop target are associated with the visual component (how do you drag if it's not visible? !). . The essence of the drag-and-drop technique is to transfer data from the drag source component to the drop target component, so at the bottom, the drag-and-drop technique is close to the clipboard technique in the above example.

Implementation of drag source: The drag source class must first create an instance of the DragGestureRecognizer, indicating that the class is a drag source component class or contains a drag source component. By calling the DataSource object createDefaultDragGestureRecognizer () method. The specific implementation is as follows:


int action = DnDConstants.ACTION_COPY_OR_MOVE; //Type of drag and drop
ds.createDefaultDragGestureRecognizer(this,action,this);

The above statement indicates that the drag source component is an instance object of the class itself, that the type of drag and drop to be done is dndconstants.action_copy_or_move, and that the class implementing the DragGestureListener interface is this class. Drag and drop sources generally implement the DragGestureListener interface, which defines a dragGestureRecognized() method. When the drag starts, the DragGestureListener listens to the event and then goes to the dragGestureRecognized() method to handle the event, such as sending the data from 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()); //Take the text of the label as the data and wrap it by the Transferable object
//Began to drag and drop, set the cursor to DragSource DefaultCopyNoDrop form, drag and drop the data object is the tr, DragSourceListener is this class
dge.startDrag(DragSource.DefaultCopyNoDrop,tr,this);
}catch(Exception err){
err.printStackTrace();
}
}

The drag source also implements the DragSourceListener interface, which defines the event handling methods for the various states associated with the drag. Methods such as dragEnter, dragOver, dropActionChanged, dragExit, etc. In this case, the dragEnter() method is implemented to set the shape of the cursor while dragging. The other methods are 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(); //Gets a context reference to the drag source
//Sets the shape of the cursor when dragging
int action = dsde.getDropAction();
if ((action&DnDConstants.ACTION_COPY)!=0)
dsc.setCursor(DragSource.DefaultCopyDrop);
else
dsc.setCursor(DragSource.DefaultCopyNoDrop);
}

Realization of placement target: The DragTarget class must first create a DragTarget instance to indicate that the class is the target component class or contains the target component, as follows:


new DropTarget(this.jTextField1,DnDConstants.ACTION_COPY_OR_MOVE,this);

The above statement indicates that the drop target is the this.jtextfield1 object, the drag-and-drop operation is dndconstants.action_copy_or_move, and the class implementing the DropTargetListener interface is this class. In contrast to DrafSourceListener, the drop target or its host class typically implements the DropTargetListener interface. The interface also defines a number of methods, such as dragEnter, dragOver, and so on, to handle events as the drag-and-drop process moves into different phases. This example is only concerned with the drop() method, that is, the event handling when the mouse is released on the target component, which is generally used to handle the data passed to. For example, the text data passed will be displayed on the JTextField component in this example. The other methods are empty methods.


public void drop(DropTargetDropEvent dtde) {
//throw new java.lang.UnsupportedOperationException("Method drop() not yet implemented.");
try{
Transferable tr = dtde.getTransferable(); //Gets the data object passed in
//Process the data object to get the text information in it
if (dtde.isDataFlavorSupported(DataFlavor.stringFlavor)){
dtde.acceptDrop(dtde.getDropAction());
String s = (String) tr.getTransferData(DataFlavor.stringFlavor);
this.jTextField1.setText(this.jTextField1.getText()+s); //Displays the text information passed from the drag-and-drop source on the drop target
dtde.dropComplete(true);
}else{
dtde.rejectDrop();
}
}catch(Exception err){
err.printStackTrace();
}
}

Program code:

1. Create a new Project called JDragAndDropDemo.
2. Create a new Application called JDragAndDropDemo; Name the main window MainFrame and title it JDragAndDropDemo.
3. Create a new Class named DragJLabel and inherit from the JLabel Class.
4. Using wizards|implements interface, the DragJLabel class implements the DragGestureListener, DragSourceListener interface.
5. Add a new property DragSource ds in the DragJLabel class, the code is as follows:


class DragJLabel extends JLabel implements DragGestureListener, DragSourceListener {
DragSource ds = DragSource.getDefaultDragSource(); //Create the DragSource instance
 ... 
}

6. Write the constructor for the DragJLabel class.


public DragJLabel(String title,int alignment){
super(title,alignment); //Use the method of the parent class
int action = DnDConstants.ACTION_COPY_OR_MOVE;
ds.createDefaultDragGestureRecognizer(this,action,this); //create
}

7. Implement the dragGestureRecognized() method in the DragJLabel class, wrapping and sending 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, and 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);
else
dsc.setCursor(DragSource.DefaultCopyNoDrop);
}

9. Add a JTextField component at the bottom of the design window of the MainFrame class and create a DragJLabel instance in the class 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() for the MainFrame class, set the initial properties of the component, and create a new DropTarget instance 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. Using wizards|implements interface, the MainFrame class implements the DropTargetListener interface.

12. Implement drop(), a method inherited from the DropTargetListener interface, to process the data passed in. 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();
}
}

Related articles: