How to create a dragging form in Java.
To implement the drag and drop functionality of a window in Java, you can follow these steps:
- Create a JFrame object and set the title and size of the window.
- Add a MouseListener and MouseMotionListener to the window to listen for mouse clicking, releasing, dragging, and other events.
- Record the coordinates of the mouse when it is clicked, and set a flag to indicate whether the window can be dragged.
- Clear the flag in the mouse release event.
- Calculate the offset of the mouse drag in the mouse drag event and update the position of the window.
Here is a simple example code implementing drag-and-drop functionality for a window.
import javax.swing.*;
import java.awt.event.*;
public class DragWindow extends JFrame {
private int lastX, lastY;
public DragWindow() {
setTitle("Drag Window Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
lastX = e.getX();
lastY = e.getY();
}
});
addMouseMotionListener(new MouseMotionAdapter() {
public void mouseDragged(MouseEvent e) {
int newX = getLocation().x + e.getX() - lastX;
int newY = getLocation().y + e.getY() - lastY;
setLocation(newX, newY);
}
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new DragWindow().setVisible(true);
}
});
}
}
By running the code above, you will see a window that can be moved by dragging the title bar.