Javafx gridpane width setting

Ooxyo picture Ooxyo · Aug 26, 2014 · Viewed 7.8k times · Source

I need to make some kind of table in which I store simple Region nodes (I will do other stuff on them afterwards - such as megring cells horizontally and giving them other properties, Labels for example) Table will have lots of columns, >200. My goal is to force every grid to have the same width (very important) and to generate that table dynamically.

Here is part of my code that generates that table.

GridPane schedule = new GridPane();

for (int j = 0; j < horizontalGridCount; ++j) {

  ColumnConstraints cc = new ColumnConstraints();
  cc.setPercentWidth(100/horizontalGridCount);
  schedule.getColumnConstraints().add(cc);
}

for (int i = 0; i < verticalGridCount; ++i) {

  for (int j = 0; j < horizontalGridCount; ++j) {

    final Region grid = new Region();
    grid.setStyle("-fx-background-color: #dddddd;");
    grid.setPrefHeight(30); // set to make regions visible on screen
    grid.setPrefWidth(10); // set to make regions visible on screen

    schedule.add(grid, j, i);

  }
}

schedule.gridLinesVisibleProperty().set(true);

Here is the output I get on my screen. As you can observe some grids are close-grained then the others

Do you have any idea why it is that wrong and how to fix that?

P.S. It's my first post here, I hope I've done everything right ;)

Answer

jewelsea picture jewelsea · Aug 26, 2014

You are using integer division logic, which rounds things. Use floating point logic instead:

cc.setPercentWidth(100.0/horizontalGridCount);

Note the 100.0 which makes 100.0 (and the division result) a non-integer.

Also don't set the grid lines visible in your target app, that setting is only for debugging (I guess this is why you have it there and set to true, but just a reminder in case):

schedule.gridLinesVisibleProperty().set(true);

If you want borders on your grid cells you can review this demo program.