2016-02-11 46 views
0

我想在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多次打電話的時候,我使用的循環?

+0

我想我們在這裏錯過了一些東西。我沒有看到paintComponent()方法在這裏的任何地方被調用。你能提供一些更多的代碼嗎? – JordyV

+0

paintComponet()不能被調用。你只能使用repaint() – dirac

+0

試試這個.repaint()。 – Svea

回答

5

repaint()方法只是請求RepaintManager來繪製組件。然後,RepaintManager將把多個請求整合到組件的單個繪畫中,以使繪畫更高效。因此,因爲所有的請求都是在你的循環中以納秒爲單位進行的,它們都被整合到一個請求中。

如果您需要某種動畫,那麼您需要使用Swing Timer來安排動畫。所以每當Timer觸發時你都會將索引加1。

+0

我嘗試在for循環中使用Tread.sleep(),但它沒有改變任何內容 – dirac

+1

@dirac請參閱答案的最後一段。你不能在這個上下文中使用'Thread.sleep',你必須使用一個Swing'Timer' – MadProgrammer