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 void 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
startXandstartY) and end coordinates (endXandendY) then it’s easy to compute the movement at each step (this code will happen in yourRunnableclass which will run in the thread):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.