Make ScrollPane Content fill Viewport Bounds

One of the most common issues I find when using ScrollPanes in JavaFX is that I need the Content to fill the width/height when the ScrollPane.ViewportBounds is larger than the Content.PrefWidth/PrefHeight.

My first thought was that the ScrollPane properties FitToWidth and FitToHeight were meant to solve this – but they force the Content to ViewportBounds even when the Content has a larger PrefWidth/PrefHeight (this is probably useful for things like a wrapped text view). I suppose it should be possible to create a conditional binding for these properties, but I haven’t looked into this.

My second thought was that maybe I could call HBox.setHgrow(content, Priority.Always) and VBox.setVGrow(content, Priority.Always), but that was ineffective.

The solution I settled on was to add a ChangeListener to ScrollPane.ViewportBoundsProperty to reset Content.MinWidth/MinHeight:

// Create ScrollPane
final ScrollPane spane = new ScrollPane(aTextArea);

// Add listener to set content min width/height from viewport bounds
spane.viewportBoundsProperty().addListener(new ChangeListener() {
  public void changed(ObservableValue<? extends Bounds> arg0, Bounds arg1, Bounds arg2) {
    if(spane.getContent() instanceof Region) {
      Region content = (Region)spane.getContent();
      content.setMinWidth(arg2.getWidth());
      content.setMinHeight(arg2.getHeight());
    }}});

Please comment if you have a better solution.

About these ads

2 Responses to “Make ScrollPane Content fill Viewport Bounds”

  1. JavaFX links of the week, June 9 // JavaFX News, Demos and Insight // FX Experience Says:

    […] The ReportMill blog has a post on how to make ScrollPane content fill the viewport bounds. […]

  2. Java desktop links of the week, June 9 « Jonathan Giles Says:

    […] The ReportMill blog has a post on how to make ScrollPane content fill the viewport bounds. […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

%d bloggers like this: