Controlling node location with AnchorPane

AnchorPane is a powerful tool for fine-tuning the resize process. It allows us to precisely attach nodes to the four sides of the window.

Imagine we are creating a browser that consists of the following components:

  • An address bar
  • Navigation buttons
  • A status bar
  • A web view:

If the browser is being resized, we want the following adaptive behavior:

  • The address bar stays on top and changes size only in the horizontal direction
  • Same for the status bar, but in the bottom
  • The web view is the most important part and should take as much space as possible
  • Buttons shouldn't resize at all, but we want them to stay at the same location

To achieve that, we put them all into AnchorPane and attach them to its borders correspondingly:

One way is to do it through an API, as in the following example:

AnchorPane root = new AnchorPane();
TextField addressAtTop = new TextField("www.stackoverflow.com");
AnchorPane.setTopAnchor(addressAtTop, 10.);
AnchorPane.setLeftAnchor(addressAtTop, 10.);
AnchorPane.setRightAnchor(addressAtTop, 10.);

But it's way more convenient to do it in FXML using the ScenicView tool we discussed in Chapter 4, FXML (note that I've removed all unrelated code to make this more readable; for the full sample, look at the GitHub file):

<!-- chapter7/resising/browser/browser.fxml -->

<AnchorPane prefHeight="324.0" prefWidth="380.0">
<children>
<WebView AnchorPane.bottomAnchor="40.0" AnchorPane.leftAnchor="14.0"
AnchorPane.rightAnchor="110.0" AnchorPane.topAnchor="51.0"/>
<TextField text="http://stackoverflow.com" layoutX="14.0" layoutY="14.0"
AnchorPane.leftAnchor="14.0" AnchorPane.rightAnchor="11.0"/>
<Button AnchorPane.topAnchor="51.0" AnchorPane.rightAnchor="11.0"
prefWidth="90.0" text="Go" />
<Button AnchorPane.topAnchor="85.0" AnchorPane.rightAnchor="11.0"
prefWidth="90.0" text="Back" />
<Label AnchorPane.bottomAnchor="14.0" AnchorPane.leftAnchor="14.0"
AnchorPane.rightAnchor="11.0" text="Status Text" />
</children>
</AnchorPane>

Now let's look at a resized application window that has followed all the rules we've set:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.15.161