If you are using Swing, likely you are putting the EDT, the Event Dispatch Thread, to sleep. This is the single thread that Swing uses to do its drawing and to interact with the user.
One solution is to use a background thread within which you can call Thread.sleep(...), but if you do this, you have to take care that most all Swing calls get called back on Event Dispatch Thread.
A safer and easier solution is to use a Swing Timer which will perform a block of code repeatedly without blocking Swing events, and all code called in this Timer gets called correctly on the EDT. Sun has a decent tutorial on this as well as of course the API both of which I suggest you read.
For instance:
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
class SimpleAnimationPanel extends JPanel
{
private static final int DELAY = 20;
public static final int X_TRANSLATION = 2;
public static final int Y_TRANSLATION = 2;
private Point point = new Point(5, 32);
private BufferedImage duke = null;
private Timer timer = new Timer(DELAY, new TimerAction());
public SimpleAnimationPanel()
{
try
{
// borrow an image from sun.com
duke = ImageIO.read(new URL(
"http://java.sun.com/products/plugin/images/duke.wave.med.gif"));
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
setPreferredSize(new Dimension(600, 400));
timer.start();
}
// do our drawing here in the paintComponent override
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
if (duke != null)
{
g.drawImage(duke, point.x, point.y, this);
}
}
private class TimerAction implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
int x = point.x;
int y = point.y;
Dimension size = SimpleAnimationPanel.this.getSize();
if (x > size.width)
{
x = 0;
}
else
{
x += X_TRANSLATION;
}
if (y > size.height)
{
y = 0;
}
else
{
y += Y_TRANSLATION;
}
point.setLocation(new Point(x, y)); // update the point
SimpleAnimationPanel.this.repaint();
}
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("SimpleAnimationPanel");
frame.getContentPane().add(new SimpleAnimationPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args)
{
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}