2016-02-12 70 views
2

我對JavaFX更新,我試圖做一個棋盤。我首先需要製作一個基於 數組的隨機顏色填充正方形的網格。我不知道爲什麼,但方格不填補網格的其餘部分。我也想使用約束來設置網格的高度和寬度。JavaFX中的正方形Gridpane

int rowNum = 10; 
int colNum = 10; 
int gridHeight = 10; 
int gridWidth = 10; 

public void start(Stage primaryStage) { 
    GridPane grid = new GridPane(); 

    //grid.getColumnConstraints().add(new ColumnConstraints(gridWidth)); 
    //grid.getRowConstraints().add(new RowConstraints(gridHeight)); 

    Random rand = new Random(); 
    Color[] colors = {Color.BLACK, Color.BLUE, Color.GREEN, Color.RED}; 

    int n = rand.nextInt(4)+1; 
    for(int row = 0; row < rowNum; row++){ 
      for(int col = 0; col < colNum; col++){ 
       Rectangle rec = new Rectangle(); 
       rec.setWidth(2); 
       rec.setHeight(2); 
       rec.setFill(colors[n]); 
       GridPane.setRowIndex(rec, row); 
       GridPane.setColumnIndex(rec, col); 
       grid.getChildren().addAll(rec); 
      } 
    } 

    Scene scene = new Scene(grid, 350, 250); 

    primaryStage.setTitle("Grid"); 
    primaryStage.setScene(scene); 
    primaryStage.show(); 
} 

只有一個正方形出現在左上角。 這是爲什麼?

+0

您使用的是相同的顏色爲所有的矩形。所以你有100個2×2的矩形,但它們看起來像一個20×20的矩形。 –

回答

2

您需要在兩個循環內移動隨機數生成步驟,以便在進入循環之前不使用與設置一次相同的顏色。另外,你不需要該隨機數發生器的加1。允許的指數是0-3。當你詢問nextInt()並輸入4時,這是獨佔的,意味着4將永遠不會被選中(這就是你需要的顏色數組)。

您的代碼應該是這樣的:

for (int row = 0; row < rowNum; row++) { 
    for (int col = 0; col < colNum; col++) { 
     int n = rand.nextInt(4); 
     Rectangle rec = new Rectangle(); 
     rec.setWidth(2); 
     rec.setHeight(2); 
     rec.setFill(colors[n]); 
     GridPane.setRowIndex(rec, row); 
     GridPane.setColumnIndex(rec, col); 
     grid.getChildren().addAll(rec); 
    } 
}