Move image to point (not drag) in Java
I have a little image in a JPanel
. When i click on the panel, the image have to move to that point.
This is the code of the mouse listener (in the constructor):
addMouseListener(new MouseAdapter(){
public vo开发者_开发百科id mouseClicked(MouseEvent e) {
if (moving) return;
moveImageTo(e.getX(), e.getY());
}
});
The moveImageTo
:
public void moveImageTo(int x, int y) {
moving = true;
moveThread.start();
}
The thread is the problem, because I have the start position (a java.awt.Point) and the end position (another java.awt.Point), but i don't know how to calculate the direction and the step of moving. I also think that the thread have to call the paint(Graphics g)
method at every step. Anyone have any hints or links?
I am guessing you don't want to move the image in one step based on your question but instead you want a "smooth" movement over a few miliseconds -- so the image appears it is sliding into position rather than moving in one go in the new position?
In that case you need to decide how long will this move take -- e.g. 500 miliseconds and how many steps you will be doing this in -- say 40 steps.
Having the start coordinates (call them startX
and startY
) and end coordinates (endX
and endY
) then it's easy to compute the movement at each step (this code will happen in your Runnable
class which will run in the thread):
...
private static final int STEPS = 40;
private static final long INTERVAL = 500;//msec
private static final long STEP_INTERVAL = INTERVAL / STEPS;
...
private int stepX, stepY;
...
public void computeMovement() {
stepX = (endX - startX) / STEPS;
stepY = (endY - startY) / STEPS;
}
...
public void run() {
int currX = startX;
int currY = startY;
computeMovement();
for( int i = 0; i < STEPS; i++ ) {
currX += stepX;
currY += stepY;
//move image to (currX, currY)
TimeUnit.MILISECONDS.sleep( STEP_INTERVAL );
}
}
The above is a very rough and ready example but it's meant to show you how you can move the image in steps within a separate thread.
Into run()
add a method to move the image a bunch pixels every refresh till you reach e.getX()
and e.getY()
. Try a bit to find a nice px/s combination
精彩评论