package swingExamples; import javax.swing.*; import java.awt.*; // a simple animation that moves a circle across the screen // adapted from Head First Java, page 384 public class SimpleAnimation { private int x, y; // circle's coordinates private JFrame frame; private PaintPanel paintPanel; private class PaintPanel extends JPanel { // called by the system when necessary to repaint( ) public void paintComponent(Graphics g ) { super.paintComponent(g); // clear the screen g.setColor(Color.white); g.fillRect(0, 0, this.getWidth(), this.getHeight()); // draw the circle in its new position g.setColor(Color.blue); g.fillOval(x, y, 40, 40); } } public SimpleAnimation( ) { frame = new JFrame("A Simple Animation"); frame.setSize( 300, 300); frame.setLocation( 200, 200); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); paintPanel = new PaintPanel(); frame.add(BorderLayout.CENTER, paintPanel); } public void launch( ) { frame.setVisible(true); for (int i = 0; i < 1; i++) { // change the circle's coordinates ++x; ++y; // force the panel to repaint itself paintPanel.repaint(); try { // wait 50ms Thread.sleep( 50 ); }catch (Exception ex) {} } } public static void main(String[] args) { SimpleAnimation animation = new SimpleAnimation(); animation.launch(); } }