1

I'm creating a chess game using Java (I'm using Swing features) and I was wondering if there is a way to get the exact location of the mouse cursor. I tried both the MouseEvent location and the java.awt.MouseInfo and in both cases the JLabel I was dragging was trailing behind the cursor. Is there a way to get the exact location? I already tried:

e.getLocationOnScreen();
MouseInfo.getPointerInfo().getLocation();

(e is the MouseEvent)

Thanks in advance

TheTompiler
  • 23
  • 1
  • 4
  • When you say "the JLabel I was dragging was trailing behind the cursor", do you mean while the mouse is moving or while it is still? One of them means lag, and the other means the coordinates are off. – MultiplyByZer0 Aug 23 '19 at 17:38
  • While the mouse was moving, the JLabel was moving as well, but a bit behind the cursor. I can provide a picture if needed – TheTompiler Aug 23 '19 at 17:51
  • What happens if you're dragging, but then you stop moving the mouse (hold it still without releasing the mouse button)? Does the JLabel still trail behind the cursor, or does it catch up? – MultiplyByZer0 Aug 23 '19 at 17:59
  • On a possibly related tangent, if you're trying to make a JLabel track the mouse to display a custom pointer image, you could consider [setting a custom Cursor](https://stackoverflow.com/a/4274653/5699679) instead. – Avi Aug 23 '19 at 18:08
  • Even if I stop the JLabel stays behind – TheTompiler Aug 23 '19 at 18:26
  • Thanks, I'll check out the custom cursor – TheTompiler Aug 23 '19 at 18:26
  • 2
    For better help sooner, [edit] to add a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). – Andrew Thompson Aug 24 '19 at 01:38

1 Answers1

0

I'd add mouse event to table. You can add for what you want that return x,y mouse location:

table.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent arg0) {
            try {
                arg0.getLocationOnScreen();
                Point r = MouseInfo.getPointerInfo().getLocation();
                System.out.println(r);
            } catch (Exception ex) {
            }
        }
    });
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Wassim Al Ahmad
  • 1,102
  • 2
  • 7
  • 23