2013-10-30 35 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); 
} 

很抱歉,如果我错了的领域。我不记得心。