Drag and Drop in Java

This tutorial will teach you how to create a drag and drop program in two textfields in java. So, now let's start this tutorial! 1. Open JCreator or NetBeans and make a java program with a file name of dragDrop.java. 2. Import the following package library:
  1. import javax.swing.*; //used to access JFrame and JTextArea class
  2. import java.awt.*; //use to access the GridLayout class
3. We will initialize variables in our Main, variable frame as JFrame, and variable textfield1 and textfield2 as JTextField.
  1. JFrame frame = new JFrame("Drag and Drop");
  2. JTextField textField1 = new JTextField(50);
  3. JTextField textField2 = new JTextField(50);
4. We will have a text for the two textfields using the setText method.
  1. textField1.setText("Drag this text to the textfield below.");
  2. textField2.setText("You can also drag this text above.");
To have a drag and drop between the two textfields, we will use the setDragEnabled method returns to True.
  1. textField2.setDragEnabled(true);
  2. textField1.setDragEnabled(true);
5. Now, we will have its layout into Grid Layout using the setLayout method of the frame.
  1. frame.getContentPane().setLayout(new GridLayout(0,1));
Add all the textfields to the frame using the add method.
  1. frame.getContentPane().add(textField2);
  2. frame.getContentPane().add(textField1);
Lastly, pack the frame, set visibility to true, and the close operation of the frame. Have this code below:
  1. frame.pack();
  2. frame.setVisible(true);
  3. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Output: output Here's the full code of this tutorial:
  1. import javax.swing.*; //used to access JFrame and JTextArea class
  2. import java.awt.*; //use to access the GridLayout class
  3. public class dragDrop {
  4. public static void main(String[] args) {
  5. JFrame frame = new JFrame("Drag and Drop");
  6. JTextField textField1 = new JTextField(50);
  7. JTextField textField2 = new JTextField(50);
  8.  
  9. textField1.setText("Drag this text to the textfield below.");
  10. textField2.setText("You can also drag this text above.");
  11.  
  12. textField2.setDragEnabled(true);
  13. textField1.setDragEnabled(true);
  14. frame.getContentPane().setLayout(new GridLayout(0,1));
  15. frame.getContentPane().add(textField2);
  16. frame.getContentPane().add(textField1);
  17.  
  18. frame.pack();
  19. frame.setVisible(true);
  20. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  21.  
  22. }
  23. }
For more inquiries and need programmer for your thesis systems in any kind of programming languages, just contact my number below. Best Regards, Engr. Lyndon Bermoy IT Instructor/System Developer/Android Developer/Freelance Programmer Mobile: 09488225971 Landline: 826-9296 E-mail:[email protected] Add and Follow me on Facebook: https://www.facebook.com/donzzsky Visit and like my page on Facebook at: https://www.facebook.com/BermzISware

Add new comment