TheGrimBoo
TheGrimBoo

Reputation: 309

Tracking the mouse movement

I am trying to make a program that tracks the mouse movement and displays the current point of the mouse into a label, but when I run my code it gave me nothing in the Jlabel

The code I used is this:

public class pr1 extends JFrame implements MouseMotionListener
{
   String Name;
   JLabel PositionLabel;
   Container cp;
   float XPosition;
   float YPosition;
   Point Point;

  public pr1 (String Name)
  {
    super (Name);
    setLayout(new FlowLayout ());
    setBackground(Color.LIGHT_GRAY);
    setSize(500, 500);
    setVisible(true);
    setResizable(false);
    setDefaultCloseOperation(EXIT_ON_CLOSE);

    PositionLabel = new JLabel ("The mouse now at the point : " );
    cp = getContentPane();
    cp.add (PositionLabel, BorderLayout.SOUTH);
  }

  @Override
  public void mouseMoved(MouseEvent e)  
  {
    Point = e.getPoint();
    PositionLabel.setText("The mouse now at the point : " + Point );
  }   

  @Override
  public void mouseDragged(MouseEvent e) 
  {
    throw new UnsupportedOperationException("Not supported yet."); 
  }
}

Upvotes: 2

Views: 84

Answers (2)

Wyatt Lowery
Wyatt Lowery

Reputation: 513

I had the same problem the other day. Take advantage of the method myComponent.getMousePosition() to get the location of the mouse (In your case, you might want to add a JPanel to the frame, then add your JLabel to the panel.).

You can use the method with a timer:

Timer t = new Timer(1, e->{
    if(myPanel.getMousePosition() != null)
        myLable.setText("The mouse now at point: " + myPanel.getMousePosition().getX() + ", " + myPanel.getMousePosition().getY());
});
t.start();

Take note that if the mouse is not on the component, getMousePosition() will return null.

Upvotes: 0

Leet-Falcon
Leet-Falcon

Reputation: 2137

You must register the component using addMouseMotionListener().
Add in the constructor:

addMouseMotionListener(this);

You can see an example at: How to Write a Mouse-Motion Listener

Upvotes: 2

Related Questions