2013-10-30 36 views
1

我有一些像這樣的代碼:如何在Java中初始化圖形?

public void paintComponent(Graphics graphics){ 
    graphics.setColor(Color.WHITE); 
    for (GameObject object : GameArea.objects){ 
     graphics.fillRect(object.position.x, object.position.y,object.width, object.height); 
    } 
    graphics.setColor(Color.BLUE); 
    graphics.fillRect(GameArea.square.position.x,GameArea.square.position.y,GameArea.square.width, GameArea.square.height); 
    for(GameObject object2 : GameArea.objects){ 
     graphics.fillRect(object2.position.x, object2.position.y,object2.width, object.height); 
    } 
} 

它是在一個叫FieldPanel類。我從MainGame類調用它是這樣的:

Timer t = new Timer(50, new ActionListener(){ 
      @Override 
      public void actionPerformed(ActionEvent e) { 
       //The following line does not work: 
       fieldPanel.paintComponent(Graphics g); 
      } 
}); 

但是,不工作的線路導致我的問題。我如何創建一個新的圖形對象傳遞給其他類的方法?而且,當我創建它時,它應該具有哪些屬性等等?我不完全確定圖形類的作用,解釋會很有幫助。自動調用

+0

1)爲了更好地提供幫助,請發佈[SSCCE](http://sscce.org/)。 2)對代碼塊使用一致的邏輯縮進。代碼的縮進旨在幫助人們理解程序流程。 –

回答

0

paintComponent(Graphics g)方法。你不能在任何地方打電話。但是,如果你想畫新的圖形,你可以在fieldPanel使用repaint()方式類似。

fieldPanel

public void draw(){ 
    GameArea.add(new GameObject()); 
    repaint(); 
} 

MainGame

Timer t = new Timer(50, new ActionListener(){ 
       @Override 
       public void actionPerformed(ActionEvent e) { 
        fieldPanel.draw(); 
       } 
    }); 
0

您可以使用雙bufferization。只是把它放在你的班級

BufferedImage bmp = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB); 
Graphics gf = bmp.getGraphics(); 

並使用此gf進行繪圖。 爲重繪使用定時器您的JComponent

Timer t = new Timer(50, new ActionListener(){ 
       @Override 
       public void actionPerformed(ActionEvent e) { 
        yourJComponent.repaint(); 
       } 
    }); 

並重寫paintComponent()喜歡你的代碼首批上市的方法:

public void paintComponent(Graphics graphics){ 
    graphics.drawImage(bmp, 
    0, 0, yourJComponent.width, yourJComponent.height, 
    0, 0, bmp.width, bmp.height, 
    null); 
} 

很抱歉,如果我錯了的領域。我不記得心。