0

I'm creating a board with many separate little squares, I want to fill the squares with the parts of the image so they go together to form the original image. How do I do that? What class should I look into? And by the way I'm drawing the board with paintComponent.

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    int boxHeight = boxHeight();
    int boxWidth = boxWidth();
    for (int row = 0; row < game.getRows(); row++) {
        for (int col = 0; col < game.getCols(); col++) {
            g.setColor(Color.lightGray);
            g.drawRect(col * boxWidth, row * boxHeight, boxWidth, boxHeight);
//this is where I want to fill the rectangles
            if (game.isAlive(row, col)) {
                g.setColor(color);
                g.fillRect(col * boxWidth, row * boxHeight, boxWidth, boxHeight);
            } 
        }
    }
}
Mike
  • 87
  • 10
  • You mean something like [this](http://stackoverflow.com/questions/11819669/absolute-positioning-graphic-jpanel-inside-jframe-blocked-by-blank-sections/11820847#11820847) or [this](http://stackoverflow.com/questions/11819669/absolute-positioning-graphic-jpanel-inside-jframe-blocked-by-blank-sections/11822601#11822601)? The trick would be to split the image (using `BufferedImage#subImage`) into smaller images and store these in something like a `List`, it will make it easier to display and manage – MadProgrammer Dec 22 '15 at 01:57

1 Answers1

0

Supposing you have a BufferedImage b:

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    int boxHeight = boxHeight();
    int boxWidth = boxWidth();
    for (int row = 0; row < game.getRows(); row++) {
        for (int col = 0; col < game.getCols(); col++) {
            g.setColor(Color.lightGray);
            g.drawRect(col * boxWidth, row * boxHeight, boxWidth, boxHeight);
//this is where I want to fill the rectangles
            if (game.isAlive(row, col)) {
                g.setColor(color);
                g.drawImage(b.getSubimage(col * boxWidth, row * boxHeight, boxWidth, boxHeight), col * boxWidth, row * boxHeight, boxWidth, boxHeight, null);
            } 
        }
    }

assuming your image is the same size as the box. Otherwise you have to shrink or expand the image:

BufferedImage b2=new BufferedImage(game.getCols()*boxWidth, game.getRows()*boxHeight, BufferedImage.TYPE_INT_RGB);
Graphics g=b2.getGraphics();
g.drawImage(b, 0, 0, b2.getWidth(), b2.getHeight(), null);

and in the loop

g.drawImage(b2.getSubimage(col * boxWidth, row * box, boxWidth, boxHeight), col * boxWidth, row * boxHeight, boxWidth, boxHeight, null);
gpasch
  • 2,672
  • 3
  • 10
  • 12