I want to add squares onto a jpanel one at a time after a delay . My program works fine until I tried to change the background color with setBackgound(). It didn't change. I worked out I have to call super.paintComponent(gr) in my paintComponent method. But when I do this and call repaint(), only the current square is displayed. The previous one's have disappeared. I know it is because repaint is displaying a whole new panel each time but why does it work when I don't call super.paintComponent(). Here is a simplified version of ghe code
import java.awt.*;
import javax.swing.*;
public class Squares extends JFrame{
aPanel ap = new aPanel();
SlowDown sd = new SlowDown(); //slows down program by given number of milliseconds
public Squares(){
super("COLOURED SQUARES");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(ap);
ap.setPreferredSize(new Dimension(300, 300));
pack();
setVisible(true);
addSquares();
}
private void addSquares(){
sd.slowDown(500);
ap.changeSquare( 100 , 100 , 255 , 0 , 0);
ap.repaint();
sd.slowDown(500);
ap.changeSquare( 200 , 200 , 0 , 0 , 255);
ap.repaint();
}
public static void main(String[] arguments) {
Squares sq = new Squares();
}
class aPanel extends JPanel{
private int x = 0;
private int y = 0;
private int r = 0;
private int g = 0;
private int b = 0;
public void paintComponent(Graphics gr) {
//super.paintComponent(gr);
Color theColor = new Color (r, g, b);
gr.setColor(theColor);
gr.fillRect(x,y,30,30);
}
void changeSquare(int i , int j, int rd , int gr , int bl){
x = i;
y = j;
r = rd;
g = gr;
b = bl;
}
}
class SlowDown{
void slowDown(long delay){
long t = System.currentTimeMillis();
long startTime = t;
while(t < startTime + delay){
t = System.currentTimeMillis();
}
}
}
}