[英]repaint() in loop only called once - Java
我試圖在JPanel上繪制網格,但是當我在循環內調用repaint方法時,它只能工作一次。 這是我的代碼:
public class Board extends JPanel{
// --- Set Density of Grid ---
public final int lines = 10;
// ---------------------------
public final int width = 600;
public final int height = 600;
public Point p1 = new Point(0,0);
public Point p2 = new Point(0,0);
public Board() {
int c0 = width/lines;
for (int j=0; j<2; j++){
int c1 = width/lines;
for (int i=0; i<lines; i++){
if (j==0){
p1 = new Point(c1,0);
p2 = new Point(c1,height);
}
if (j==1){
p1 = new Point(0,c1);
p2 = new Point(width,c1);
}
c1 = c1 + c0;
repaint();
}
}
}
public void drawGrid(Graphics g){
g.drawLine(p1.x, p1.y, p2.x, p2.y);
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
drawGrid(g);
System.out.println("Inside");
}
}
這是輸出:
Inside
使用for循環時,如何多次調用paintComponent方法?
repaint()
方法只是向RepaintManager
發出請求以繪制組件。 然后, RepaintManager
將把多個請求合並到組件的單個繪制中,以使繪制更有效。 因此,由於您的所有請求都是在循環中彼此之間相差幾毫秒之內完成的,因此它們全部合並為一個請求。
如果要某種動畫,則需要使用Swing計時器來安排動畫。 因此,每次計時器觸發時,您都將索引加一。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.