我想在延迟后一次将正方形添加到 jpanel 上。在我尝试使用 setBackgound() 更改背景颜色之前,我的程序运行良好。它没有改变。我发现我必须在我的 paintComponent 方法中调用 super.paintComponent(gr)。但是当我这样做并调用 repaint() 时,只显示当前方块。以前的方块消失了。我知道这是因为 repaint 每次都显示一个全新的面板但是为什么当我不调用 super.paintComponent() 时它会起作用。这是代码的简化版本:
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();
}
}
}
}