It’s not all gold and sunshine; JavaFX layout
After my previous post, praising the properties and binding mechanism, I’d also like to voice an opinion on something on which I think the JavaFX team has dropped the ball.
In the previous post about Agenda control I explained that there were two ways I updated the nodes in Agenda; either I setup binding in the constructor, or I listen to relevant properties and call a relayout() method, setting the appropriate values there. Especially the binding is a powerful feature. No software engineer can deny that the sniplets below don’t have a certain beauty to them.
Adding a rectangle that serves as a dragger at the bottom of an appointment:
durationDragger.xProperty().bind(widthProperty().multiply(0.25)); // 25% offset from the left border durationDragger.widthProperty().bind(widthProperty().multiply(0.5)); // 50% of the width of the appointment durationDragger.yProperty().bind(heightProperty().subtract(5)); // 5 pixels from the bottom border durationDragger.setHeight(3); // 3 pixels high
Making sure the day head and day body line up:
header.getChildren().add(dayHeader); week.getChrildren().add(dayBody); dayHeader.xProperty().bind( dayBody.xProperty()); dayHeader.widthProperty().bind( dayBody.widthProperty());
What is important here is that the x,y,w,h values are set directly on the children. The container does not do any layout, it simply draws its childeren where they say they want to be. This is called an ‘absolute’ layout. All other layouts (VBox, HBox, BorderPane, …) do not want you to set the x,y,w,h of the children, their added value is that they’ll calculate and set them for you. (more…)