javaswinguser-interfacemouselistenermousemotionlistener

how to drag an image around starting from the mouse position , in Java?


So I am a new Java programmer and I am trying to learn how to deal with GUI and moving images around using JLabel

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

I am trying to lean how to :

1- start dragging from the mouse position that i click on ?

2-dragging only if the mouse is on the image bounds not on all JLabel ?


Solution

  • dragging only if the mouse is on the image bounds not on all JLabel ?

    Add the listener to the label, not the frame.

    start dragging from the mouse position that i click on ?

    Determine the starting point when the label is clicked and calculate the change in mouse location with each event. Basic code is:

    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);
         }
    }
    

    The code to use this class would be:

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