如何设置 JavaFX 滚动窗格的最大大小并使滚动条仅在需要时显示



我正在尝试构建一个单一窗口应用程序来更好地了解JavaFX。这很好,很容易,直到我没有进入细节......

我有一个锚窗格作为其他 GUI 元素的主要容器。我意识到,它对于我的笔记本电脑屏幕来说太高了(805 像素高,600 像素宽(,所以我决定在缩小窗口时将锚窗格放在滚动窗格中以具有滚动条。AnchorPane在FXML中配置,ScrollPane在Java源代码中配置。

锚窗格:

<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">

滚动窗格:

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);
}

}

然后,我加载 FXML,将锚窗格放在滚动窗格中,让它显示:

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) {
        LOG.error("Error loading GUI!", e);
    }
}

到目前为止一切顺利,窗口显示并且没有滚动条,直到我不缩小它。但是我想最大化我的窗口,因为它没有意义让它变大(锚窗格有一个固定的大小(,只是更小。我已经想通了,必须设置主舞台的最大大小来限制实际窗口,限制滚动窗格不起作用。

这就是问题所在:如果我想为 PrimayStage 设置最大高度和最大宽度,我只会得到不需要的结果。如果我希望我的主舞台具有与锚窗格相同的最大大小,则窗口要么不显示,要么有滚动条!

如果我把这一行放在我的 InitWindow mehtod 中

        // Show the scene containing the layout.
        Scene scene = new Scene(scrollableMainFrame);
        primaryStage.setScene(scene);
        // set max window size
        primaryStage.setMaxHeight(scrollableMainFrame.getHeight());
        primaryStage.show();

什么都不会出现,因为显然"可滚动大型机"在这一点上没有高点。

如果我把 setMaxHeight(( 放在最后,比如

    primaryStage.setScene(scene);
    primaryStage.show();
    // set max window size
    primaryStage.setMaxHeight(scrollableMainFrame.getHeight());

然后,将有效地设置最大高度,但滚动条会出现并保持可见,即使窗口具有其完整大小!

有谁知道为什么,以及我如何在没有滚动条的情况下为我的窗口设置最大大小?

(简单地将数字加到最大值,就像primaryStage.setMaxHeight(scrollableMainFrame.getHeight() + 15); 一样根本没有做任何事情,滚动条仍然存在!

谢谢,James_D,你引导我找到解决方案!

确实如您所说,滚动条出现,因为主舞台还包含标题栏,我忘记了。这让我思考:如何根据其内容计算窗口的全尺寸,以将其设置为最大大小?好吧,我不需要!逻辑有些扭曲,但有效:我只需要询问主舞台的实际大小,并将其设置为最大值。诀窍是,我需要在创建窗口后执行此操作:

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

最新更新