how to make a label follow the pointer, within a frame with a mouse event?

0

I have tried again and again to move a jlabel to the position where the pointer is located. for this I have captured the coordinates of the pointer and I have assigned them to my label.

    private void jPanel1MouseMoved(java.awt.event.MouseEvent evt) {                                   
   ///coordenadas es un jlabel que me sirve para mostrar las coordenadas donde se encuentra el puntero
   coordenadas.setText(String.format("Sus coordenadas son: [%d ,%d]", evt.getX(), evt.getY()));
   x=evt.getX();
    y=evt.getY();

    ///llegador es mi label que deceo mover a la posicion donde se encuentra mi puntero
    llegador.setLocation(x,y);

}    

but it turns out that the "llegador" label does not change position (it does not move). if they helped me, I would appreciate it a lot.

thanks in advance

    
asked by tristan romero 21.11.2017 в 23:57
source

1 answer

0

I have a Swing app to which I have included functionality of that style, with mouse events.

The first thing I have are two global variables:

private Point location;
private MouseEvent myEvent;

Later I applied to a component 2 listeners ( mousePressed and mouseDragged ):

display.addMouseListener( new MouseAdapter() {
  public void mousePressed( MouseEvent evt ) {
    myEvent = evt;
  }
} );

display.addMouseMotionListener( new MouseAdapter() {
  public void mouseDragged( MouseEvent evt ) {
    Component C = evt.getComponent();
    location = C.getLocation( location );
    int x = location.x - myEvent.getX() + evt.getX();
    int y = location.y - myEvent.getY() + evt.getY();
    display.setLocation( x, y );
  }
} );

That way I move (drag) the component wherever the cursor reaches inside the container.

    
answered by 22.11.2017 / 04:11
source