At the beginning I'd like to stress, that I'm quite new to Java and I always try to find the answer for my questions myself, but sometimes it happens that I reach the dead-end and that's why I'd like to ask you if you have an idea for that.
I try to make a card game. I would like to do a quite simply thing (in my opinion) that is, move a JLabel with an image of a card back from one point to another inside a JPanel that is parent to it, in a serie of moves with the delay of 40ms to create an "animation" of dealing the card.
However as I try to do it, I get duplications of the card despite of the fact that I refresh the parent JPanel. I've been searching for an answer how to do it for a long time until now and nothing worked for me. I tried to refresh the JLabel with the card itself, its parent JPanel too, but without any effects.
The only partial solution was to repaint the JPanel, that is a parent to this JPanel with JLabel, but it caused flickering of my whole GUI which is not acceptable. Only then, there was no duplications like this presented in the image I enclose here.
Note: I use absolute layout, however I'm aware of the fact how unprofessional it is. It's just because I don't know how to comply with the rest of my layout using another manager.
I'd be very grateful for any hints or solutions you may have for me.
Image presenting what I would like to achieve
Image presenting the current situation
public void moveCard()
{
// move the card to x = 0 (its destination) inside the parent panel
while (movedCard.getX() != 0)
{
// try to reach x = 0
// as the starting x cannot be divided through 20 it must subtract 21 once at the end
if (movedCard.getX() == 21)
{
movedCard.setLocation(movedCard.getX() - 21, movedCard.getY());
}
else
{
movedCard.setLocation(movedCard.getX() - 20, movedCard.getY());
}
// repaint the panel that the card is drawn on
movedCard.getParent().paintComponents(movedCard.getParent().getGraphics());
// wait until the card is moved for the next time
try
{
Thread.sleep(40);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
// set the location of the card to default
movedCard.setLocation(341, movedCard.getY());
}
}