"I am having trouble working out how to insert the grid into the jpanel as this is more complicated than expected. I have tried many things but havent had any luck..Any help?"
Not sure what exactly you're trying to or what you're doing wrong, but one thing I can suggest is to use JLabel
s. They take text as parameters, which show the text in the label. JPanel
s on the other hand, need to be drawn on (meaning you need to actually draw the text yourself).
Test out this program, to see what I'm talking about
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class DrawGrid {
public DrawGrid() {
int[][] grid = getGrid();
JPanel panel = new JPanel(new GridLayout(10, 10));
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
panel.add(new JLabel(String.valueOf(grid[i][j])));
}
}
JFrame frame = new JFrame();
frame.add(panel);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public int[][] getGrid() {
int[][] grid = new int[10][10];
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
grid[i][j] = i;
}
}
return grid;
}
public static void main(String[] args) {
new DrawGrid();
}
}
Here's the code where I add the JLabel
s to the JPanel
JPanel panel = new JPanel(new GridLayout(10, 10));
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
panel.add(new JLabel(String.valueOf(grid[i][j])));
}
}
The same way you add borders and background to the JPanel
, you can also do with JLabel