Java implements the mouse to drag and drop the function the method _java

Source: Internet
Author: User
Tags gettext

This article describes the Java use of mouse drag and drop to implement the Exchange program data, the so-called mouse drag-and-drop function. The drag-and-drop function of the mouse is very common in graphical systems, and Java provides JAVA.AWT.DND and Java.awt.datatransfer packages to support this feature. This example shows how to implement a drag-and-drop implementation in a program when the "Hello world!" at the top of the window tab, and drag to the bottom of the window to let go of the text box, then add "Hello world!" in the text box. text; Continue with the above procedure and continue adding the text.

The realization of the program function is as follows: in the implementation of mouse drag and drop, the two most important concepts are drag-and-drop source and drop target. The drag source and drop target are all associated with the visual component (if not visible, how can you drag it?!) )。 The essence of drag-and-drop technology is to pass data on the drag source component to the drop target component, so from the bottom up, drag-and-drop is close to the Clipboard technique in the example above.

drag-and-drop source implementation: Drag the source class you must first create a Draggesturerecognizer instance that indicates that the class is a drag-and-drop Source component class or contains a drag source component. Can be implemented 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 indicates that the drag-and-drop source component is an instance object of the class itself, the type of drag-and-drop is dndconstants.action_copy_or_move type, and the class that implements the Draggesturelistener interface is this class. Drag-and-drop source general implementation of the Draggesturelistener interface, which defines a draggesturerecognized () method, when the start of the drag is, Draggesturelistener heard the event, Then go to the draggesturerecognized () method to handle the event, such as sending data from the dragged source. Specific code:

public void draggesturerecognized (Draggestureevent dge) {
//throw new java.lang.UnsupportedOperationException (" Method Draggesturerecognized () is not yet implemented. ");
try{
Transferable tr = new StringSelection (This.gettext ());//Label text as data, wrapped by transferable object
//start dragging, Sets the cursor to Dragsource.defaultcopynodrop, and the dragged data is a TR object, Dragsourcelistener is the class
Dge.startdrag ( dragsource.defaultcopynodrop,tr,this);
} catch (Exception err) {
err.printstacktrace ();
}
}

Drag-and-drop sources also have to implement the Dragsourcelistener interface, which defines the drag-and-drop event-handling methods associated with each state. such as DragEnter, DragOver, dropactionchanged, Dragexit and other methods. In this case, the DragEnter () method is implemented to set the cursor shape when dragged, and the other method is null. 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 contextual reference to the drag source
//Set the cursor shape when dragging the
int action = Dsde.getdropaction ();
if ((action&dndconstants.action_copy)!=0)
dsc.setcursor (dragsource.defaultcopydrop);
else
dsc.setcursor (dragsource.defaultcopynodrop);
}

implementation of the drop target: the class in which the drop target must first create a Dragtarget instance to indicate that this class is to place the target component class or include the drop target component, as follows:

New DropTarget (This.jtextfield1,dndconstants.action_copy_or_move,this);

The above statement indicates that the drop target is a This.jtextfield1 object, the drag-and-drop operation is Dndconstants.action_copy_or_move, and the class that implements the Droptargetlistener interface is this class. In contrast to Drafsourcelistener, a Droptargetlistener interface is generally implemented by placing the target or the class in which it resides. The interface also defines a number of methods, such as DragEnter, DragOver, and so on, to handle events when a drag-and-drop process enters a different phase. This example concerns only the drop () method, which is typically used to handle the data passed when the mouse is released on the drop target component, as in this case the text data passed on the JTextField component is displayed, and the other method is null, 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 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); Displays the text message passed from the drag source
Dtde.dropcomplete (True) on the drop target;
else{
Dtde.rejectdrop ();
}
catch (Exception err) {
err.printstacktrace ();
}
}

Program code:

1. Create a new project named Jdraganddropdemo.
2. Create a new application, named Jdraganddropdemo; the main window is named Mainframe and the title is Jdraganddropdemo.
3. Create a new class, named Dragjlabel, and inherit the JLabel class.
4. Use wizards|implements interface to make the Dragjlabel class implement Draggesturelistener, Dragsourcelistener interface.
5. Add a new attribute to the class Dragjlabel DragSource DS with the following code:

Class Dragjlabel extends JLabel implements Draggesturelistener, Dragsourcelistener {
DragSource ds = Dragsource.getdefaultdragsource (); Create DragSource instance ...
}

6. Write the construction method for the Dragjlabel class.

Public Dragjlabel (String title,int alignment) {
super (title,alignment);//Using 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 to wrap and send data.

public void draggesturerecognized (Draggestureevent dge) {
//throw new java.lang.UnsupportedOperationException (" Method Draggesturerecognized () is 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);
else
dsc.setcursor (dragsource.defaultcopynodrop);
}

9. Add a JTextField component to the lower part of the design window of the mainframe class and create a Dragjlabel instance in the class with the following specific code:

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 for the mainframe class Jbinit (), set the component's initial properties, and create a new DropTarget instance with the following code:

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));
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 Droptargetlistener interface.

12. Implement the Method drop () that inherits from the Droptargetlistener interface, processing the passed data, the specific code is as follows:

 public void drop (Droptargetdropevent dtde) {//throw new java.lang.UnsupportedOperation
Exception ("Method drop () is 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 Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.