Drag/Moving a shape around jPanel

China☆狼群 提交于 2019-12-01 08:19:21
int x = e.getX(), y = e.getX();

This should probably be changed to

int x = e.getX(), y = e.getY();

That's why it only works in the x direction, you aren't actually taking into account the Y direction

Yes, in order to drag components you also need to know the starting location so you can calculate the distance the mouse has moved.

Here is some code that shows this general behaviour for moving a window.

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;

public class MoveWindow extends MouseInputAdapter
{
    Point location;
    MouseEvent pressed;

    public void mousePressed(MouseEvent me)
    {
        pressed = me;

    }

    public void mouseDragged(MouseEvent me)
    {
        Component component = me.getComponent();
        location = component.getLocation(location);
        int x = location.x - pressed.getX() + me.getX();
        int y = location.y - pressed.getY() + me.getY();
        component.setLocation(x, y);
     }

    private static void createAndShowGUI()
    {
        JWindow window = new JWindow();
        window.setSize(300, 300);
        window.setLocationRelativeTo( null );
        window.setVisible(true);

        MouseInputAdapter listener = new MoveWindow();
        window.addMouseListener( listener );
        window.addMouseMotionListener( listener );

    }

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                createAndShowGUI();
            }
        });
    }
}

I'll let you implement it for your purposes.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!