Search code examples
javaswinguser-interfacelabelmouselistener

Moving the label in Java


I wanted to make a label and move it on the screen. I tried to find some videos and other sources to find how to do so but couldn't understand them well, or they used things I never heard of. So I made this code (the frame is extending JFrame and implementing MouseListener):

This is the main Class:

public class Main {

    public static void main(String[] args) {
        new Frame();
    }
}

And this is the class with the code:

public class Frame extends JFrame implements MouseListener{

    JLabel label;

    Frame() {
        label = new JLabel();

        label.setBounds(800, 200, 200, 200);
        label.setBackground(Color.RED);
        label.setOpaque(true);
        label.addMouseListener(this);

        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setSize(1200, 700);
        this.setLayout(null);
        this.add(label);
        this.setVisible(true);
        this.setLocationRelativeTo(null);
    }
    @Override
    public void mouseReleased(MouseEvent e) {
        Point x = e.getPoint();
        label.setLocation(x);
        System.out.println(x);
    }

When I try to move the label, the label moves, but not in the place I want it to. Only sometimes, the label moves in the direction I want to, but most of the time, it moves in any random direction. Even if I just click, it moves. However, even if the label moves in the direction I want to, it goes to a random length in the direction.


Solution

  • You can do that by using a MouseListener to track when the mouse is pressed and get the coordinates of the label, alongside a MouseMotionAdapter to track when the mouse is moved (or dragged) to help you set the new location of the label.

    Update: To add more info on how this works, e.getLocationOnScreen().x returns the X coordinate of the mouse pressed based on the computer screen, while label.getX() returns the X coordinate of the label based on the Java Swing container it has been added to; in this case, that is the JFrame. So, one has to subtract that value from the previous one to get the actual X coordinate of the label on the screen. Same applies for the Y coordinate. Once you have both coordinates, you can use the label.setLocation() method to change the location of the label, and hence, move the label around the screen.

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    
    public class LabelDragExample extends JFrame {
        JLabel label;
        int x, y;
    
        public LabelDragExample() {
            label = new JLabel();
            label.setBounds(800, 200, 200, 200);
            label.setBackground(Color.RED);
            label.setOpaque(true);
            label.addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    x = e.getLocationOnScreen().x - label.getX();
                    y = e.getLocationOnScreen().y - label.getY();
                }
            });
            label.addMouseMotionListener(new MouseMotionAdapter() {
                @Override
                public void mouseDragged(MouseEvent e) {
                    label.setLocation(e.getLocationOnScreen().x - x, e.getLocationOnScreen().y - y);
                    x = e.getLocationOnScreen().x - label.getX();
                    y = e.getLocationOnScreen().y - label.getY();
    
                }
            });
            this.setDefaultCloseOperation(EXIT_ON_CLOSE);
            this.setSize(1200, 700);
            this.setLayout(null);
            this.setVisible(true);
            this.add(label);
            this.setLocationRelativeTo(null);
        }
    
        public static void main(String[] args) {
    
            new LabelDragExample();
    
        }
    }