如何将打印到控制台的类添加到JPanel

时间:2016-07-15 05:55:10

标签: java random jpanel

我有这个类随机创建彼此相邻的房间,并打印到控制台的括号(代表房间)。但是我想知道如何将这样的东西添加到用于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();
        }
    }
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您可能想要使用java.awt.Graphics。它可以让你绘制线条,矩形,圆形等原始形状。This可能会让你开始。第2节还介绍了如何在JPanel上绘图。