dkchetan dkchetan - 1 month ago 11
Java Question

Mouse Coordinates keep getting on top of one another -Java

I am trying to get the mouse coordinates display in the panel but each time I move the cursor the message and new coordinates are being displayed on the previous one.I am using MouseMotionListener with JPanel. I can't figure out the problem.
enter image description here

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.MouseMotionListener;
public class Main extends JPanel implements MouseMotionListener {
public JLabel label;
public static void main(String[] args) {
new Main();
JFrame frame = new JFrame();
frame.setTitle("MouseCoordinates");
frame.setSize(400, 400);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
Container contentPane = frame.getContentPane();
contentPane.add(new Main());
frame.setVisible(true);
}
public Main() {
setSize(400, 400);
label = new JLabel("No Mouse Event Captured", JLabel.CENTER);
add(label);
addMouseMotionListener(this);
}
public void mouseMoved(MouseEvent e) {
label.setText("Mouse Cursor Coordinates => X:" + e.getX() + " |Y:" + e.getY());
}
public void mouseDragged(MouseEvent e) {}
}

Answer

You're creating Main twice.

public class Main extends JPanel implements MouseMotionListener {
public JLabel label;

public static void main(String[] args) {
    Main m = new Main();// create an object and reference it
    JFrame frame = new JFrame();
    frame.setTitle("MouseCoordinates");
    frame.setSize(400, 400);
    frame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent we) {
            System.exit(0);
        }
    });
    Container contentPane = frame.getContentPane();
    contentPane.add(m);
    frame.setVisible(true);
}
//...

your problem was creating the Main object twice (which is a jpanel) and then the writing appeared twice. if you give the Main object a reference, then your problem should be fixed.