I don't think the accepted answer is the right one. Setting the anchors in an AnchorPane
does what it says in the documentation (setBottomAnchor
):
If set, the anchorpane will maintain the child's size and position so
that its bottom is always offset by that amount from the anchorpane's
bottom content edge.
But that's not what is desired. It is to arrange things so that the child and parent are the same size.
The important thing to appreciate, from my experiments, is that a parent Node
will accept and adapt to the width and height (preferred width? preferred height?) of its child/children... if you tell it to. In other words, the mechanism works in the contrary direction to the one you might assume: the parent can be told to adapt to the child, not the child to the parent.
With an HBox
containing a ScrollPane
containing an AnchorPane
containing a TextArea
, using SceneBuilder, this does what the question is looking for:
<HBox prefHeight="100.0" prefWidth="200.0">
<children>
<ScrollPane prefHeight="100.0">
<content>
<AnchorPane>
<children>
<TextArea fx:id="logTextArea" prefWidth="800.0">
</TextArea>
</children>
</AnchorPane>
</content>
</ScrollPane>
</children>
</HBox>
Note that there is no use of anchors, and above all that the ScrollPane
and the AnchorPane
have no "preferred width" setting.
In SceneBuilder, the thing to adjust here for the ScrollPane
and the AnchorPane
is in the right-hand panel/concertina, under "Layout: ...:" choose the ScrollPane
, and set "Pref Width" to "USE_COMPUTED_AREA". Then choose the AnchorPane
and do the same. Finally, choose the TextArea
and set this to your choice, e.g. in my case 800 (pixels). Obviously this setting can be adjusted to something more sophisticated in your code if you want.
You will then see that the parent Node
of the TextArea
(AnchorPane
) and grandparent Node
(ScrollPane
) adjust to accommodate the TextArea
.
Note that the prefWidth
setting of the HBox
then gets ignored. It is the normal job of a container like an HBox
to accommodate its descendants, and it would only be if you set its maxWidth
to something incompatible with the requirements of its descendants that that constraint would then apply.
If you set a grandchild Node
like this with a prefWidth
of 800, I assume there is some way of calculating the width, under normal circumstances, of the grandparent ScrollPane
: this will be something to do with settings of borders, padding, margins and the like, in all three components involved. Note the protected
method in class Region
, computePrefWidth
, intended for subclasses to override, which may be of interest.
Plus, in the case of ScrollPane
, the presence or absence of vertical and/or horizontal scrollbars, as and when these appear. If you set wrapText
to true
on the TextArea
you might hope that a horizontal scrollbar will never appear. My experiments seem to show that you also need to set ScrollPane
's fitToWidth
Property
to true
.