jeudi 14 juillet 2016

How to add a class that prints to the console on to a JPanel

I have this class that randomly creates rooms next to each other, and prints brackets (which represent the rooms) to the console. But I wanted to know how to add something like that to a JPanel for a GUI. Here is the room generator class:

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] ? "[]" : "  ");
        }
    }
}

Thanks for the help!




Aucun commentaire:

Enregistrer un commentaire