2016-10-09 48 views
0

我正在寫一個遊戲,其中我需要隨機顏色的磚塊。迄今爲止,這是我的進步。我有一個類磚,AllBricks,並重寫paint方法爲JPanelJava:無法繪製()從一個數組中的每個項目

private static class Brick { 
    static int x; 
    static int y; 
    static Color color; 

    Brick(int _x, int _y, Color _color){ 
     x = _x; 
     y = _y; 
     color = _color; 
    } 

    void paint(Graphics g) { 
     g.setColor(Color.WHITE); 
     g.drawRoundRect(x, y, BRICK_SIZE, BRICK_SIZE, BRICK_ARC_SIZE, BRICK_ARC_SIZE); 
     g.setColor(color); 
     g.fillRoundRect(x + 1, y + 1, BRICK_SIZE-2, BRICK_SIZE-2, BRICK_ARC_SIZE-1, BRICK_ARC_SIZE-1); 
    } 
private static class AllBricks { 
    private ArrayList<Brick> bList = new ArrayList<>(); 

    AllBricks(){ bList.clear(); } 

    void add (Brick b){ bList.add(b); } 

    void paint(Graphics g) { 
     if(bList.size()>0) { 
      for (Brick brick : bList) brick.paint(g); 
     } 
    } 
} 
private static class GameField extends JPanel { 
    @Override 
    public void paintComponent(Graphics g) 
    { 
     super.paintComponent(g); 
     allBricks.paint(g); 
    } 
} 

而現在,當我把我的主循環,增加新的模塊,並試圖拉攏他們,我只看到最後添加的塊,但不是全部......

private void loop() 
{ 
    while (true) { 
     delay.wait(1000); 

     Brick b1 = new Brick(random.nextInt(WIN_WIDTH - BRICK_SIZE), random.nextInt(WIN_HEIGHT - BRICK_SIZE), COLORS.get(random.nextInt(COLORS.size() - 1))); 
     allBricks.add(b1); 
     mainField.repaint(); 
    } 
} 

請問您能幫我保存以前在屏幕上畫的塊嗎?

+1

'您能否幫助我保存屏幕上以前繪製的塊?' - 您需要重新繪製所有每次組件重新粉刷時都會顯示磚塊。此外,您應該重寫面板的「paintComponent(...)」,而不是paint()。另一種選擇是繪製一個'BufferedImage'。查看[自定義繪畫方法](https://tips4java.wordpress.com/2009/05/08/custom-painting-approaches/)以獲取有關此主題的更多信息和工作示例。 – camickr

+0

現在,當我重寫paintComponent時 - 沒有任何更改..是的,我調用allBlocks.paint()方法遍歷數組中的所有塊,並將其稱爲.paint(); – Vanechka

+0

我什麼都不知道,你仍然需要修改你的代碼。你錯過了我最重要的第一個聲明!您還錯過了閱讀鏈接中信息的要點。 – camickr

回答

1

你的磚x和y座標不應該是靜態的。由於它是靜態的,所有的磚塊都有一個共享的x和y值(所以所有的磚塊都被繪製在相同的位置)

相關問題