0

I have a problem which I have to solve with my code. So I have a checkerboard and when I click on something I want to drag around (i.e. checker), I make visible a label which holds picture of it (I know it ain't the neat solution but I was told to do it so) in a proper place calculated by a fomula. I wanted to use the same formula to be able calculate coordinates of the checker under mouseDragged event but here's the problem. If I just set the location of the label by simple getX() or getY() from the event then it's top left corner is "jumping" under my mouse pointer as soon as I move the mouse. I'd like it to stick to the cursor in the place I clicked it, so I did something like this:

    public void mouseDragged(MouseEvent evt) {
        int col = (evt.getX() - 4) / 40;
        int row = (evt.getY() - 4) / 40;
        int setX = evt.getX()-(col*40);
        int setY = evt.getY()-(row*40);
        if (dragged)
            inv.setLocation(evt.getX()-setX+42, evt.getY()-setY+37);

where col is the X coordinate of the column I want to drage the checker from (and so is the row) and setX is just a variable I'm using below. And these calculations seem to be ok to me, but they make me able only to drage the checker in a manner where it doesn't move at all (like I was dragging something transparent) and when I enter finally a new place on the board it's being painted there and so on. Not a fluent drag but it's being consequently drawn in the fields under my cursor during dragging.

The +42 and + 37 are just some numbers to calcualte it in proper place since the board isn't starting from (0,0).

  • See also this [example](http://stackoverflow.com/a/2562685/230513) and [variation](http://stackoverflow.com/a/2563350/230513). – trashgod Jun 24 '13 at 19:35

1 Answers1

1

The reason the corner of the checker is "jumping" to your mouse is because of the way images are drawn. When you set the coordinates of the image you are setting the point P(0,0) of the image, which is the top-left corner when drawn on a screen.

To fix this issue, in addition to keeping track of the row and column number, you need to keep track of the x and y offset (in pixels) you want to maintain though the mouse movement in each checker board "cell".

This means when you click, you might click the checker in row 2, column 3, with an (x, y) offset of (12,14). I am assuming your squares are larger than 14x14 pixels.

I turned your 42 into BOARD_X_OFFSET and 37 into BOARD_Y_OFFSET I have added two doubles cellX and cellY which hold the offset within the cell.

This will make your set location look similar to this:

inv.setLocation(evt.getX()-setX+BOARD_X_OFFSET+cellX, evt.getY()-setY+BOARD_Y_OFFSET+cellY);
Zycro
  • 81
  • 9