I am currently learning JavaFX and I came across a very strange API for laying out GUI components. It is perhaps best explained by it's javadoc:
To use the GridPane, an application needs to set the layout constraints on the children and add those children to the gridpane instance. Constraints are set on the children using static setter methods on the GridPane class:
GridPane gridpane = new GridPane(); // Set one constraint at a time... // Places the button at the first row and second column Button button = new Button(); GridPane.setRowIndex(button, 0); GridPane.setColumnIndex(button, 1); // or convenience methods set more than one constraint at once... Label label = new Label(); GridPane.setConstraints(label, 2, 0); // column=2 row=0 // don't forget to add children to gridpane gridpane.getChildren().addAll(button, label);
Applications may also use convenience methods which combine the steps of setting the constraints and adding the children:
GridPane gridpane = new GridPane(); gridpane.add(new Button(), 1, 0); // column=1 row=0 gridpane.add(new Label(), 2, 0); // column=2 row=0
I am wondering what the purpose of having layout data be given in such a strange manner (ie. the first set of methods) rather than only offering the "convenience methods which combine the steps."
This seems odd for several reasons:
- Swing, the only other GUI library I know in detail has everything passed in as part of it's add() method in it's GridBagLayout which seems to be roughly equivalent to GridPane.
- It isn't obvious in what object the GridPane.setConstraints() method is actually storing it's data. I doubt it is in the actual component object as it wouldn't make much sense for every component to have member variables for a layout that may or may not be in use at any given time and the method doesn't have any reference to the specific GridPane in use so it can't add it there either.
- Other JavaFX layouts have something much more similar to what seems logical to me, giving layout data to the layout pane in the add method, with the BorderPane's setCenter(), setLeft(), etc. methods.