I have two classes, one where the grid is set and the other where a GUI is made. I want the grid from the first class to be inserted into jPanel in the second class. The first grid is a char grid and is filled with numbers that are randomly initiated. 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?
//set grid class
public void setgrid() {
Random ran = new Random();
for (int i = 0; i < X; i++) {
for (int j = 0; j < Y; j++) {
int num = ran.nextInt(10);
if (num == 4) {
grid[i][j] = 'F';
} else if (num == 9) {
grid[i][j] = 'O';
} else {
grid[i][j] = ' ';
}}}
// Panel Class
Panel = new JPanel(new GridLayout(X, Y));
for (int i = 0; i < X; i++) {
for (int j = 0; j < Y; j++) {
world[i][j] = new JPanel();
world[i][j].setBackground(Color.white);
world[i][j].setBorder(BorderFactory
.createLineBorder(Color.black));
Panel.add(world[i][j]);
NOT SURE WHAT TO ADD HERE TO ADD THE GRID INTO THE PANEL
Not sure what exactly you're trying to or what you're doing wrong, but one thing I can suggest is to use
JLabels. They take text as parameters, which show the text in the label.JPanels 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
Here's the code where I add the
JLabels to theJPanelThe same way you add borders and background to the
JPanel, you can also do withJLabel