2016-07-15 112 views
0

我有这个类随机创建彼此相邻的房间,并将括号(表示房间)打印到控制台。但我想知道如何在GUI中添加类似于JPanel的东西。这里是房间发生器类:如何将打印到控制台的类添加到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(); 
     } 
    } 
} 

感谢您的帮助!

回答

0

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