我想在延迟后一次添加一个正方形到jpanel上。我的程序运行良好,直到我尝试使用setBackgound()更改背景颜色。它并没有改变。我计算出我必须在我的paintComponent方法中调用super.paintComponent(gr)。但是当我这样做并调用displayed.The ()时,只有当前的正方形消失了,前一个正方形已经消失了。我知道这是因为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();
}
}
}
}发布于 2012-07-15 13:26:43
因此,您可以做许多事情来改进代码。首先,如果您想要绘制许多矩形并“记住”这些矩形,那么您需要存储在过去绘制的矩形。否则,每次基本上都会在之前绘制的矩形上进行绘制。因此,我建议将每个矩形存储在某种列表中。然后在画图上,你可以遍历列表并画出每个矩形。
其次,可以通过调用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
}
}现在,上面的示例将允许您不断地向列表中添加新的矩形,并且每次绘制所有的矩形。如果您需要将每个矩形绘制为不同的颜色,那么您可能需要创建自己的rectangle类来存储在列表中。至于延迟,你可以这样做:
class SlowDown{
void slowDown(long delay){
Thread.sleep(delay);
}
}这应该会让事情暂停几毫秒。
https://stackoverflow.com/questions/11489592
复制相似问题