package com.daimafans.fun;

import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * 拖拽事件
 *
 * @author liuqianfei
 */
public class DraggedListener extends MouseAdapter
{

    // 这两组x和y为鼠标点下时在屏幕的位置和拖动时所在的位置
    int newX, newY, oldX, oldY;
    // 这两个坐标为组件当前的坐标
    int startX, startY;

    @Override
    public void mousePressed(MouseEvent e)
    {
        // 此为得到事件源组件
        Component cp = (Component) e.getSource();
        // 当鼠标点下的时候记录组件当前的坐标与鼠标当前在屏幕的位置
        startX = cp.getX();
        startY = cp.getY();
        oldX = e.getXOnScreen();
        oldY = e.getYOnScreen();
    }

    @Override
    public void mouseDragged(MouseEvent e)
    {
        Component cp = (Component) e.getSource();
        // 拖动的时候记录新坐标
        newX = e.getXOnScreen();
        newY = e.getYOnScreen();
        // 设置bounds,将点下时记录的组件开始坐标与鼠标拖动的距离相加
        cp.setBounds(startX + (newX - oldX), startY + (newY - oldY), cp.getWidth(), cp.getHeight());
    }

    @Override
    public void mouseReleased(MouseEvent e)
    {
        Component cp = (Component) e.getSource();
        Component parent = cp.getParent();

        newX = e.getXOnScreen();
        newY = e.getYOnScreen();
        int x = cp.getX();
        int y = cp.getY();
        if (x < 0)
        {
            x = 0 + 1;
        }
        if (y < 0)
        {
            y = 0 + 1;
        }
        if (x > parent.getWidth() - cp.getWidth())
        {
            x = parent.getWidth() - cp.getWidth();
        }
        if (y > parent.getHeight() - cp.getHeight())
        {
            y = parent.getHeight() - cp.getHeight();
        }
        if (x != cp.getX() || y != cp.getY())
        {
            cp.setBounds(x, y, cp.getWidth(), cp.getHeight());
        }
    }
}