Java Swing How to - Drag and drop between two JTextField








Question

We would like to know how to drag and drop between two JTextField.

Answer

//  ww w.j  a  va  2  s.  c o m
import java.awt.Container;

import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main extends JFrame {

  public static void main(String[] args) {
    new Main().setVisible(true);
  }

  public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTextField field1 = new JTextField("Life's a drag", 20);
    JTextField field2 = new JTextField("and then you drop", 20);
    field1.setDragEnabled(true);
    field2.setDragEnabled(true);
    Container content = getContentPane();

    content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
    content.add(field1);
    content.add(field2);

    pack();
  }
}