Peter1
Peter1

Reputation: 167

Display mouse cordinates on jPanel

I want to display mouse cordinates using drawString() method when I move the mouse. Here is my current code. This works for mouseClicked(MouseEvent e) method but not for mouseMoved(MouseEvent e) method. Can someone help me with this please?

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test extends JFrame {

    public Test() {
        PaintLocaion paintlocation = new PaintLocaion();
        paintlocation.setSize(400,300);
        add(paintlocation, BorderLayout.CENTER);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       
    }

    public static void main(String[] args) {
        new Test().setVisible(true);
    }

    private class PaintLocaion extends JPanel {
        int x, y;

        public PaintLocaion() {          
            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseMoved(MouseEvent e) {
                    x = e.getX();
                    y = e.getY();
                    repaint();
                }
            });
        }      

        @Override
        public void paint(Graphics g) {
            super.paint(g);
            g.fillRect(0, 0, this.getWidth(), this.getHeight());
            g.setColor(Color.white);
            g.drawString(x + ", " + y, 10, 10);
        }
    }     
}

Upvotes: 0

Views: 94

Answers (2)

MadProgrammer
MadProgrammer

Reputation: 347184

Instead of registering a MouseListener you need to register a MouseMotionListener...

public PaintLocaion() {          
    addMouseMotionListener(new MouseAdapter() {
        @Override
        public void mouseMoved(MouseEvent e) {
            x = e.getX();
            y = e.getY();
            repaint();
        }
    });
}      

See How to write a Mouse-Motion Listener for more details

Updated from comments by mKorbel

There are issues with overriding paint, while it might seem like the logical thing to do, the area begin updated by the paint method may not be update when a repaint occurs and you can end up with some weird paint issues.

It's recommended to use paintComponent instead.

If you're trying to paint over the top components, you might consider using the glass pane or JXLayer/JLayer instead

Take a look at Painting in AWT and Swing for more details about the paint process. How to use root panes for details about the glass pane and How to Decorate Components with the JLayer Class

Upvotes: 4

wedens
wedens

Reputation: 1830

you can try to use MouseMotionListener http://docs.oracle.com/javase/tutorial/uiswing/events/mousemotionlistener.html

Upvotes: 2

Related Questions