如何在Java中从鼠标位置开始拖动图像?

时间:2017-04-27 16:17:25

标签: java swing user-interface mouselistener mousemotionlistener

所以我是一名新的Java程序员,我正在尝试学习如何使用JLabel处理GUI和移动图像

public class MyJava extends JFrame implements MouseListener, MouseMotionListener {
JLabel aJLabel;

public MyJava() {
    this.setLayout(null);
    aJLabel = new JLabel();
    ImageIcon aImageIcon = new ImageIcon(this.getClass().getResource("avatar.jpg"));
    aJLabel.setIcon(aImageIcon);
    aJLabel.setBounds(50, 50, 200, 150);
    this.getContentPane().add(aJLabel);
    this.addMouseListener(this);
    this.addMouseMotionListener(this);
    this.setTitle("Title");
    this.setSize(700, 600);
    this.setLocationRelativeTo(null);
    this.setVisible(true);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String[] args) {
    new MyJava();
}
@Override
public void mouseClicked(MouseEvent e) {
    System.out.println("mouseClicked, X=" + e.getX() + " ,Y=" + e.getY() + " ,Count=" + e.getClickCount());
}
@Override
public void mouseDragged(MouseEvent e) {
    aJLabel.setBounds(e.getX()-120, e.getY()-120, 200, 150);
}
@Override
public void mousePressed(MouseEvent e) {
    System.out.println("mousePressed");
}
@Override
public void mouseReleased(MouseEvent e) {
    System.out.println("mouseReleased");
}
@Override
public void mouseEntered(MouseEvent e) {
    System.out.println("mouseEntered");
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
    System.out.println("mouseMoved");
}}

enter image description here

我正在努力学习如何:

1-从我点击的鼠标位置开始拖动?

只有当鼠标位于图像边界而不是所有JLabel上时才进行2次拖动?

1 个答案:

答案 0 :(得分:1)

  

仅当鼠标位于图像边界而不是所有JLabel上时才拖动?

将侦听器添加到标签,而不是帧。

  

从我点击的鼠标位置开始拖动?

确定单击标签时的起点,并计算每个事件的鼠标位置变化。基本代码是:

public class DragListener 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);
     }
}

使用此类的代码为:

DragListener drag = new DragListener();
label.addMouseListener( drag );
label.addMouseMotionListener( drag );