Zach J February 2016

How to set the maximum size of a JavaFX ScrollPane and make Scrollbars appear only when needed?

I'm trying to build a single window application to get to know JavaFX better. It was quite nice and easy, until I did not get into the details...

I have an AnchorPane as a main container of the other GUI elements. I realized, that it is too high for my laptop screen (805 px high, 600 px wide), so I decided to put the AnchorPane inside a ScrollPane to have scroll bars, when I shrink the window. The AnchorPane is configured in FXML, the ScrollPane in Java source code.

The AnchorPane:

<AnchorPane maxHeight="805.0" prefHeight="805.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.jzoli.mp3checker.view.MainWindowController">

...

The ScrollPane:

public class ScrollableMainFrame extends ScrollPane {

public ScrollableMainFrame(Pane content) {
    super();

    // set scrollbar policy
    this.setHbarPolicy(ScrollBarPolicy.AS_NEEDED);
    this.setVbarPolicy(ScrollBarPolicy.AS_NEEDED);

    // set the main window in the scroll pane
    this.setContent(content);
}

}

I then load the FXML, put the AnchorPane inside the Scrollpane, and let it show:

private final void initWindow() {
    try {
        // Load main window layout from fxml file.
        URL mainWindowURL = MainApp.class.getResource("view/MainWindow.fxml");
        FXMLLoader loader = new FXMLLoader(mainWindowURL, guiLabels);
        mainWindow = (AnchorPane) loader.load();
        MainWindowController controller = loader.getController();
        controller.setMainAppAndGUILabels(this);

        // create a scrollable Pane, and put everything inside
        scrollableMainFrame = new ScrollableMainFrame(mainWindow);

        // Show the scene containing the layout.
        Scene scene = new Scene(scrollableMainFrame);
        primaryStage.setScene(scene);            
        primaryStage.show();
    } catch (IOException e) {
            

Answers


Zach J February 2016

Thanks, James_D, you lead me to the solution!

It is indeed as you said, scrollbars appear, because the PrimaryStage also contains the title bar, which I forgot. This made me think: how can I calculate the full size of a window based on its content, to set it as a max size? Well, I don't need to! The logic is somewhat twisted, but works: I simply need to ask the Primarystage for its actual size, and set it as a maximum. The trick is, that I need to do that after the window has been created:

        // create the window
        primaryStage.show();
        // set actual size as max
        primaryStage.setMaxHeight(primaryStage.getHeight());
        primaryStage.setMaxWidth(primaryStage.getWidth());

Post Status

Asked in February 2016
Viewed 3,087 times
Voted 14
Answered 1 times

Search




Leave an answer