-2

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] + ";");
        }
    }
}
  • One way is to put panes (or maybe labels, or whatever) in a grid pane and use CSS... You should try something and post some actual code if you can't get it to work. – James_D Apr 24 '17 at 17:17
  • Ok. Thanks. I'm working on it, but it looks awful :)) – Valentin Emil Cudelcu Apr 24 '17 at 17:18
  • You may be interested in this interesting project [Sudoku grabber and solver using OpenCV, JavaFX and Scala](https://github.com/rladstaetter/sudokufx), although it is kind of advanced and may confuse you (and won't help you at all with the issue in your question), it is very clever. – jewelsea Apr 25 '17 at 00:40
  • @jewelsea Thanks. I'll take a look. I nedd to improve my backtracking algorithm. – Valentin Emil Cudelcu Apr 25 '17 at 20:08

1 Answers1

2

Instead of all those if-else constructs you can use

int colorIndex = 3 * (row / 3) + (col / 3);
cell.setStyle("-fx-background-color: " + colors[colorIndex] + ";");

Note that row / 3 is calculated using integer division, so row / 3 is 0 when row is in {0, 1, 2}, 1 when row is in {3, 4, 5}, and 2 when row is in {6, 7, 8}. (So 3 * (row / 3) is not equal to row. )

James_D
  • 201,275
  • 16
  • 291
  • 322