2016-07-15 95 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。

相關問題