我想在JPanel上繪製一個網格,但是當我在循環中調用repaint方法時,它只能工作一次。這裏是我的代碼:repaint()在循環中只調用一次 - Java
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
我怎樣才能在方法的paintComponent多次打電話的時候,我使用的循環?
我想我們在這裏錯過了一些東西。我沒有看到paintComponent()方法在這裏的任何地方被調用。你能提供一些更多的代碼嗎? – JordyV
paintComponet()不能被調用。你只能使用repaint() – dirac
試試這個.repaint()。 – Svea