Tristus
Tristus

Reputation: 143

Using .setLocation() dosent seem to be working for JLabel

So im trying to display a grid of bitmap tiles on a window. I have a for loop that is populating the array of JLabels and using .setLocation() to define their position. The problem is that when the frame is displayed, they seem to totally ignore the location that ive set for them.

Heres my code so far.

public static void main(String[] args) throws IOException {
    JFrame mainFrame = new JFrame("game.demo");

    mainFrame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
    mainFrame.setSize(512, 512);

    JPanel mainPanel = new JPanel();

    BufferedImage desTile16Image = ImageIO.read(new File("assets//desert_tile_16x.bmp"));
    ImageIcon desTile16Icon = new ImageIcon(desTile16Image);

    JLabel[][] map = new JLabel[32][32];




    for (int x = 0; x < 32; x++) {
        System.out.print(x + "\n");
        map[x][0] = new JLabel();
        map[x][0].setIcon(desTile16Icon);
        map[x][0].setLocation(x * 16, 0);
        mainPanel.add(map[x][0]);
    }

    //mainFrame.pack();
    mainFrame.add(mainPanel);
    mainFrame.setContentPane(mainPanel);
    mainFrame.setVisible(true);
}

any help would be greatly appreciated, thanks in advance.

Upvotes: 0

Views: 53

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347194

Consider something like...

JPanel mainPanel = new JPanel(new GridLayout(32, 32));

Then you won't need map[x][0].setLocation(x * 16, 0);

Take a look at Laying Out Components Within a Container and How to Use GridLayout more details

Upvotes: 1

Related Questions