我希望在延迟后一次一个地添加方块到jpanel上。我的程序运行正常,直到我尝试使用setBackgound()更改背景颜色。它没有改变。我搞定了,我必须在paintComponent方法中调用super.paintComponent(gr)。但是当我这样做并调用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();
}
}
}
}
答案 0 :(得分:0)
因此,您可以采取一些措施来改进代码。首先,如果你想绘制一些矩形并“记住”矩形,那么你需要存储过去绘制的矩形。否则会发生的是你每次都基本上在先前绘制的矩形上绘画。所以我建议将每个矩形存储在某种List中。然后在绘画上,您可以遍历列表并绘制每个矩形。
其次,延迟可以通过Thread.sleep()调用完成。也许这将是一个例子:
class APanel extends JPanel{
List<Shape> rects;
private int r = 0;
private int g = 0;
private int b = 0;
public APanel(){
rects = new ArrayList<Shape>();
}
public void paintComponent(Graphics gr) {
super.paintComponent(gr);
Color theColor = new Color (r, g, b);
gr.setColor(theColor);
for(Shape s: rects){
((Graphics2D)gr).fill(s);
}
}
void changeSquare(int i , int j, int rd , int gr , int bl){
rects.add(new Rectangle2D.Double(i, j, 30, 30));
//we have to deal with colors
}
}
现在,上面的示例将允许您不断向列表中添加新的矩形,并且每次都绘制所有矩形。如果需要以不同的颜色绘制每个矩形,则可能必须创建自己的矩形类以存储在List中。至于延迟,你可以这样做:
class SlowDown{
void slowDown(long delay){
Thread.sleep(delay);
}
}
这应该暂停几毫秒。