jeudi 30 juin 2016

Image is not displaying propertly

I am trying to make 2D array of JPanels that will contain images. Everything compiles well, but the last square in the bottom right corner. I was trying to fix this, but as I see for me it's impossible. This is the code that I actually have:

ImagePanel.java:

import java.awt.Graphics;
import java.awt.image.BufferedImage;

import javax.swing.BorderFactory;
import javax.swing.JPanel;

public class ImagePanel extends JPanel {
    private static final long serialVersionUID = 1423049366366931156L;
    private BufferedImage image;

    public ImagePanel(BufferedImage i) {
        image = i;
        this.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
    }

    public void newImage(BufferedImage i) {
        image = i;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, null);
    }
}

As You see, my ImagePanel class is well. Thats how i declare it:

final int BOARD_X = 25;
final int BOARD_Y = 15;
ImagePanel[][] PanelBoard = new ImagePanel[BOARD_X][BOARD_Y];

And I fill (and add to form) afterwards using the following code:

for (int i = 0; i < BOARD_Y; ++i) { //y
    for (int i2 = 0; i2 < BOARD_X; ++i2) { // x
        PanelBoard[i2][i] = new ImagePanel(textures[0]);
        PanelBoard[i2][i].setBounds(i2 * 48, i * 48, 48, 48);
        PanelBoard[i2][i].setVisible(true);
        add(PanelBoard[i2][i]);
    }
}

The textures array is simply an array that contains arrays of buffered images (that are actually loaded properly).

Everything seems to look good, but the last square doesn't show.

So, my question is: how can I make this code work, and properly display the last square in the bottom right corner?

EDIT:

This code fixed my problem, but I cant figure out why:

PanelBoard[BOARD_X-1][BOARD_Y-1] = new ImagePanel(textures[0]);
        PanelBoard[BOARD_X-1][BOARD_Y-1].setBounds(BOARD_X*48, BOARD_Y*48, 48, 48);
        PanelBoard[BOARD_X-1][BOARD_Y-1].setVisible(true);
        add(PanelBoard[BOARD_X-1][BOARD_Y-1]);

Aucun commentaire:

Enregistrer un commentaire