Java - Add background to every square in a 9x9 grid

时间:2017-04-24 17:16:03

标签: javafx background grid sudoku

I would like to make in JavaFX a 9x9 sudoku grid like in this image

enter image description here

Any idea how to do it in a nice way? Thanks

Edit: I managed to do it, but the code doesn't look so good.

private void addBackground(StackPane cell, int row, int col) {
    String[] colors = {"#b0cbe1", "#cbe183", "#e18398","#b0e183", "#b8778a", "#e198b0", "#b08398", "#cb98b0", "#e1b0cb"};
    if(row < 3) {
        if(col < 3) { 
            cell.setStyle("-fx-background-color: " + colors[0] + ";");
        } else if (col >= 3 && col < 6 ) {
            cell.setStyle("-fx-background-color: " + colors[1] + ";");
        } else{
            cell.setStyle("-fx-background-color: " + colors[2] + ";");
        }
    } else if (row >= 3 && row <6) {
        if(col < 3) { 
            cell.setStyle("-fx-background-color: " + colors[3] + ";");
        } else if (col >= 3 && col < 6 ) {
            cell.setStyle("-fx-background-color: " + colors[4] + ";");
        } else {
            cell.setStyle("-fx-background-color: " + colors[5] + ";");
        }
    } else {
        if(col < 3) { 
            cell.setStyle("-fx-background-color: " + colors[6] + ";");
        } else if (col >= 3 && col < 6 ) {
            cell.setStyle("-fx-background-color: " + colors[7] + ";");
        } else{
            cell.setStyle("-fx-background-color: " + colors[8] + ";");
        }
    }
}

1 个答案:

答案 0 :(得分:2)

您可以使用

代替所有if-else结构
int colorIndex = 3 * (row / 3) + (col / 3);
cell.setStyle("-fx-background-color: " + colors[colorIndex] + ";");

请注意,row / 3是使用整数除法计算的,因此当行在{0,1,2}时row / 3为0,当行在{3,4,5}时为1,并且2当行在{6,7,8}时。 (所以3 * (row / 3)不等于row。)

相关问题