2013-03-06 85 views
1

我想弄清楚我的程序的行爲,這是我最好的理論,爲什麼它做它的事情。我希望這將使用rand變量來決定繪製哪種形狀,但相反,似乎paintComponent方法在定時器點火之間被多次調用,導致許多形狀被繪製,我試圖理解爲什麼。在Graphics2D上調用drawRect方法是否觸發paintComponent方法?

這是代碼:

public class TestPane extends JPanel { 

    private int yPos0; 
    private int yPos1; 
    private int boundary0=750; 
    private ActionEvent ae = null; 
    private Graphics g0 = null; 
    private int count=1; 

    public TestPane(Color foreground){ 
     setForeground(foreground); 
     this.setBackground(Color.BLUE); 
     Timer timer = new Timer(3000,new ActionListener(){ 
      @Override 
      public void actionPerformed(ActionEvent e){ 
       ae = e; 
       yPos0 =yPos0+50; 
        repaint(); 
      } 
     }); 
     timer.start(); 
    } 

    @Override 
    public void paintComponent(Graphics g){ 
      g0 = g; 
      super.paintComponent(g); 
      createShape(yPos0); 
      repaint(); 
    } 

    public void createShape(int ypos0){ 
     //generate random number between 1 and 3 and assign to rand 
     int rand = (int)((Math.random()*3)+1); 

     System.out.println(rand); 
     if(rand==1){ 
      Graphics2D g2d = (Graphics2D) g0.create(); 
      g2d.setColor(Color.RED); 
      g2d.drawRect(0, ypos0, 200, 50); 
     } 

     if(rand==2){ 
      Graphics2D g2d = (Graphics2D) g0.create(); 
      g2d.setColor(Color.GREEN); 
      g2d.drawRect(0, ypos0, 150, 50); 
      g2d.drawRect(50, ypos0+50,50,50); 
     } 
    } 
} 

回答

3

之所以paintComponent被稱爲這麼多次的是,你在呼喚導致本身方法中repaint被稱爲循環往復。這不是必需的,因爲您已從Timer呼叫repaint

+0

哇,這是我的頭顱。謝謝陌生人 – 2013-03-06 20:35:35

相關問題