Monday, June 25, 2012

JavaFX 2.0 Layout Panes - AnchorPane

An AnchorPane is similar to a BorderPane (see my previous post JavaFX 2.0 Layout Panes - BorderPane) as it also provides several areas or regions for your nodes.

In contrast to a BorderPane, an AnchorPane provides only four different regions: Left, Right, Bottom and Top (a BorderPane additionally provides a center region).

There are several more major differences between the two panes:

  • In an AnchorPane you can anchor multiple nodes to one area (in a BorderPane you can only set one node to each area).
  • In an AnchorPane you can anchor one single node to multiple areas, i.e. anchoring a Button to the left and the top of the AnchorPane, whereas in a BorderPane every node can only be applied to one area.
  • In an AnchorPane you can specify the offset to the anchor.
  • A BorderPane provides instance methods to populate each area (i.e. setCenter(Node node), setRight(Node node), ...). An AnchorPane offers static methods like AnchorPane.setTopAnchor(Node node, Double offset) that are applied directly to a Node.
  • In a BorderPane each child will grow and shrink with its parent depending on the area it is applied to. In an AnchorPane children will only be resized/stretched if they are anchored to opposite sides of the pane. For example if a Button is anchored to the left and the right anchor of an AnchorPane, the Button will be stretched horizontally.

Please take a look at this first simple example: