如何创建对象以形成行和列

时间:2017-06-03 04:10:28

标签: java

我正在创建基本的Brick游戏。我的问题是如何创建砖块,使它们形成的行和列整齐地堆叠在一起。我知道有很多类似的问题,但我是新的,我无法理解如何做到这一点,我希望有人可以告诉我如何做到这一点,所以我可以学习。谢谢。

Game.java

public class Game extends Canvas implements Runnable{
  private Bricks bricks;

  public void init(){
   bricks = new Bricks(200, 200, this);
  }

  public void run(){
  intit();
  //Game Loop

 }

 public void tick(){
  bricks.tick();
 }

 public void render() {
    BufferStrategy bs = this.getBufferStrategy();
        if(bs == null){
            createBufferStrategy(3);
            return;
        }

        Graphics g = bs.getDrawGraphics();
        g.drawImage(background, 0, 0, getWidth(), getHeight(), this);

        bricks.render(g);

        g.dispose();
        bs.show();
}


}

Bricks.java

public class Bricks {

private double x, y;

Game game;
private Image BrickImg;


public Bricks(double x, double y, Game game) {
    this.x = x;
    this.y = y;
    this.game = game;

    ImageIcon bricksImg = new ImageIcon("res\\bricks.png");
    BrickImg = bricksImg.getImage();
}

public void tick() {

}

public void render(Graphics g) {
    g.drawImage(BrickImg, (int)x, (int)y, null);
}

}

1 个答案:

答案 0 :(得分:1)

一种选择是用JLabel表示每个砖块。这是一个例子:

public class Game extends JPanel{

    private final static int ROWS = 10;
    private final static int COLS = 10;
    private final static int GAP = 2;

    Game(){

        setLayout(new GridLayout(ROWS, COLS,GAP, GAP));
        for (int row = 0 ; row < ROWS; row++) {
            for (int col = 0; col < COLS; col++) {
                add(new Brick());
            }

        }
    }

    public static void main(String[] args)  {

        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        f.add(new Game());
        f.pack();
        f.setVisible(true);
    }

}

class Brick extends JLabel{

    Brick() {

        Icon bricksImg = new ImageIcon("res\\bricks.png");
        setIcon(bricksImg);
    }
}

enter image description here