What if you want to change a drawing to display something else? The answer is that you provide a method in the drawing class which changes the data, and then calls the repaint() method.
...
class Brick extends JPanel
{
Rectangle rectangle;
...
void change(int x, int y, int width, int height)
{
rectangle = new Rectangle(x,y,width,height);
repaint();
}
...
}
The repaint() method does not immediately redraw the picture, because that might be impossible (e.g. if the frame window is covered up). Instead, it tells the graphics thread that the picture has changed and should be redrawn at the next suitable opportunity.
Here's a suitable main program which displays the original brick, waits five seconds, then displays a new brick.
...
class ExpandingBrick implements Runnable
{
...
public static void main(String[] args)
{
ExpandingBrick program = new ExpandingBrick();
SwingUtilities.invokeLater(program);
try { Thread.sleep(5*1000); }
catch (InterruptedException e) { }
brick.change(160,120,80,60);
}
...
}
This is a very simple example of animation. The sleep call is done in the main program thread, which usually just gets discarded. Such calls must not be done in the graphics thread, because that would freeze the application. For more sophisticated animation, you would normally set up a separate thread for controlling timings, e.g. using the Timer class in javax.swing. See the Java tutorial for more info.