Java Program to enable drag and drop between two text fields in Java

Java 8Object Oriented ProgrammingProgramming

Yes, we can enable drag and drop between two text fields in Java. Let us first create two JTextFields and set content in it as shown below −

JTextField one = new JTextField(20);
one.setText("You can drag!");
JTextField two = new JTextField(20);
two.setText("Drag here or there");

Now, we will enable and drag and drop for both the components created above −

one.setDragEnabled(true);
two.setDragEnabled(true);

The following is an example to enable drag and drop between two text fields −

Example

package my;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JFrame frame = new JFrame("Demo");
      JLabel label;
      frame.setLayout(new FlowLayout());
      label = new JLabel("Drag and Drop the two TextFields below: ", SwingConstants.LEFT);
      JTextField one = new JTextField(20);
      one.setText("You can drag!");
      one.setDragEnabled(true);
      JTextField two = new JTextField(20);
      two.setText("Drag here or there");
      two.setDragEnabled(true);
      frame.add(label);
      frame.add(one);
      frame.add(two);
      Container content = frame.getContentPane();
      content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
      content.add(one);
      content.add(two);
      frame.setSize(600,250);
      frame.setVisible(true);
   }
}

Output

Now, we will drag from TextField 1 to the 2nd TextField. We have dragged successfully above −

raja
Updated on 30-Jul-2019 22:30:26

Advertisements