So I found this code here, it works, it just causes quite a lot of juddering – (the faster you drag the more the image shakes) – in the image when it’s dragged. OP said it wasn’t optimized and since it’s a dead post I thought I’d see if anyone here could help! I’ve also tried the code from stack, but I couldn’t get it to do anything. If anyone has any suggestions for this code, or a better solution I’d love to hear it!
OF note, my Jpanel that needs to be dragged around (paintComponent drawn object) is inside a scrollpane!
//initial reference point
private Point mouseLocation;
public void mousePressed(MouseEvent evt){
mouseLocation = evt.getPoint();
}
public void mouseDragged(MouseEvent evt){
//current mouse location
Point newLoc = evt.getPoint();
//deltas
int deltaX = newLoc.x-mouseLocation.x;
int deltaY = newLoc.y-mouseLocation.y;
p.setLocation(p.getX()+deltaX,p.getY()+deltaY);
//move the reference point to the current location
this.mouseLocation = newLoc;
}
Here is a sample program that shows the juddering!
Then I would say that it does not work. And if you read the post carefuly, the OP also states that it does not work.
Moreover, the button does not strictly follows the mouse, so it’s just horrible in my opinion.
Now, two things to consider:
evt.getPoint(): the value of that method is relative to theJButton. As you move theJButtonaround, you cannot compare the value of that method with the previous one (since your button is moving). One simple solution is to convert those points relatively to a fixed panel, for example the parent, which is not moving. Tadaam: it works smoothly now and the button follows your mouse perfectly.setLocation(nor setBounds or setSize()) because this is the job of LayoutManager’s, and as soon as they will re-layout your container, the button will be set back to its original location (which I am guessing you don’t want). There are several ways to solve this, but usually, the simplest one is to use absolute positionning (ie, set the layout tonull). In the end, this means that you have to perform yourself whatever the LayoutManager was previously doing.Here is a small demo (which is flawed but demonstrates basic princiles):