我有这个类随机创建彼此相邻的房间,并打印到控制台的括号(代表房间)。但是我想知道如何将这样的东西添加到用于GUI的JPanel中。这是房间发电机类:
public class Rooms {
static final int width = 15, height = 10;
static final int rooms = 19;
static boolean[][] room = new boolean[width][height];
static int neighborCount(int x, int y) {
int n = 0;
if (x > 0 && room[x-1][y]) n++;
if (y > 0 && room[x][y-1]) n++;
if (x < width-1 && room[x+1][y]) n++;
if (y < height-1 && room[x][y+1]) n++;
return n;
}
public void Rooms() {
room[width/2][height/2] = true;
Random r = new Random();
int x, y, nc;
for (int i = 0; i < rooms; i++) {
while (true) {
x = r.nextInt(width);
y = r.nextInt(height);
nc = neighborCount(x, y);
if (!room[x][y] && nc == 1) break;
}
room[x][y] = true;
}
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++)
System.out.print(room[x][y] ? "[]" : " ");
System.out.print();
}
}
}
感谢您的帮助!