Monday, June 23, 2025

[JAVA] JAVA DRAG

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Rectangle2D;
import java.util.ArrayList;
import java.util.List;

public class DragPanel extends JPanel implements MouseListener, MouseMotionListener {

    private List<DraggableShape> shapes = new ArrayList<>();
    private DraggableShape selectedShape = null;
    private double offsetX, offsetY;

    public DragPanel() {
        // Add a sample shape
        shapes.add(new DraggableShape(new Rectangle2D.Double(50, 50, 100, 75), Color.BLUE));

        addMouseListener(this);
        addMouseMotionListener(this);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D) g;
        for (DraggableShape shape : shapes) {
            g2.setColor(shape.getColor());
            g2.draw(shape.getShape());
        }
    }

    @Override
    public void mousePressed(MouseEvent e) {
        double mx = e.getX();
        double my = e.getY();

        for (DraggableShape shape : shapes) {
            if (shape.getShape().contains(mx, my)) {
                selectedShape = shape;
                offsetX = mx - shape.getShape().getX();
                offsetY = my - shape.getShape().getY();
                break;
            }
        }
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        if (selectedShape != null) {
            double newX = e.getX() - offsetX;
            double newY = e.getY() - offsetY;
            Rectangle2D currentShape = (Rectangle2D) selectedShape.getShape();
            currentShape.setFrame(newX, newY, currentShape.getWidth(), currentShape.getHeight());
            repaint();
        }
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        selectedShape = null;
    }

    // Unused MouseListener/MouseMotionListener methods
    @Override public void mouseClicked(MouseEvent e) {}
    @Override public void mouseEntered(MouseEvent e) {}
    @Override public void mouseExited(MouseEvent e) {}
    @Override public void mouseMoved(MouseEvent e) {}

    // Helper class for draggable shapes
    private static class DraggableShape {
        private Shape shape;
        private Color color;

        public DraggableShape(Shape shape, Color color) {
            this.shape = shape;
            this.color = color;
        }

        public Shape getShape() { return shape; }
        public Color getColor() { return color; }
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("Drag Example");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new DragPanel());
        frame.setSize(400, 300);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

No comments: