In this section, you will learn how to make a component draggable in java. This program provides the drag and drop feature from one component to another. This program shows a text box and a label on the frame. When you drag the label and drop to the text box then the text of the label is copied to the text box. For the pictorial representation of the application result is given as follows:
There are several APIs has been used to make the component draggable in the program. These are explained as follows:
This is the class of the javax.swing.*; package. This is used to transfer the transferable swing component from on the another. Both components should be the swing component. This class is helpful to copy from one component to another via clipboard.
This is the method of the TransferHandler class which makes the component able to transfer the specified part of the component in the TransferHandler() as parameter which specifies the the property of the component which has to be dragged and dropped. This program specifies the text of the label to be dragged and drop to the text box using the string "text".
This is the interface which receives the different mouse events. Mouse events can be like: pressing or releasing the mouse, click, enter or exit the mouse etc. are handled through the MouseEvent generated by the MouseListener interface. This program uses the instance of the MouseListener.
This is the method of the TransferHandler class which initiates the component to drag and drop from one to another swing component. This method takes three arguments like: JComponent, Active event, and another is the Action which has to be done. Here, the constant property COPY of the TransferHandler class has been used to copy the text from the label to the text box.
Here is the code of the program:
We have 1000s of tutorials on our website. Search Tutorials tutorials on our website.
Posted on: April 14, 2007 If you enjoyed this post then why not add us on Google+? Add us to your Circles