JPanel Drag - Java Swing

Java examples for Swing:JPanel

Description

JPanel Drag

Demo Code


//package com.java2s;

import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
    public static void panelDrag(final JFrame frame, JPanel pane) {
        MouseAdapter moveWindowListener = new MouseAdapter() {

            private Point lastPoint = null;

            @Override//w  w  w.  j  av a 2s  .  c om
            public void mousePressed(MouseEvent e) {
                lastPoint = e.getLocationOnScreen();
            }

            @Override
            public void mouseDragged(MouseEvent e) {
                Point point = e.getLocationOnScreen();
                int offsetX = point.x - lastPoint.x;
                int offsetY = point.y - lastPoint.y;
                Rectangle bounds = frame.getBounds();
                bounds.x += offsetX;
                bounds.y += offsetY;
                frame.setBounds(bounds);
                lastPoint = point;
            }

        };
        pane.addMouseListener(moveWindowListener);
        pane.addMouseMotionListener(moveWindowListener);
    }
}

Related Tutorials