I have a maze creator program and want to put it into a gui. My maze is in a 2D array, so i planned to create a 2D array of JLabels in a JPanel and assign each label a color based on whether it's a path or a wall. I can create the 2D array of JLabels and add it to my panel, but when I run it all the JLabels shift right one space so I have a blank space in my top left corner and there is one more column and one less row than there's suppose to be.
Picture of the GUI:
Here's my code; I'm not sure what the issue is. I've tried altering the size of the GridLayout, changing how many times my loops run, altering the value of row and col (both are 10 right now), and tried manually creating an extra JLabel in that spot, but no dice.
public Maze() {
JPanel panel = new JPanel();
getContentPane().add(panel);
int row = MazeCreator.r;
int col = MazeCreator.c;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 500, 500);
getContentPane().setLayout(new GridLayout(row, col));
JLabel[][] grid= new JLabel[row][col];
for (int i = 0; i < row; i++){
for (int j = 0; j < col; j++){
grid[i][j] = new JLabel();
grid[i][j].setBorder(new LineBorder(Color.BLACK));
//grid[i][j].setBackground(Color.black);
grid[i][j].setOpaque(true);
super.add(grid[i][j]);
}
}
grid[0][0].setBackground(Color.red);
}
I can "fix" the too few rows and too many cols issue by subtracting 1 from col and add 1 to row, but that will only create 99 JLabels instead of 100 and, like I said, manually putting in the top left JLabel does not work.
Do not use super.add()
to add your labels to the panel. And set your panel's layout to GridLayout
not JFrame
's.
public Maze() {
JPanel panel = new JPanel();
getContentPane().add(panel);
int row = MazeCreator.r;
int col = MazeCreator.c;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 500, 500);
panel.setLayout(new GridLayout(row, col));
JLabel[][] grid= new JLabel[row][col];
for (int i = 0; i < row; i++){
for (int j = 0; j < col; j++){
grid[i][j] = new JLabel();
grid[i][j].setBorder(new LineBorder(Color.BLACK));
//grid[i][j].setBackground(Color.black);
grid[i][j].setOpaque(true);
panel.add(grid[i][j]);
}
}
grid[0][0].setBackground(Color.red);
}