我正在尝试构建一个单一窗口应用程序,以更好地了解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);
}
}
到目前为止一切顺利,窗口出现了,没有滚动条,直到我不缩小它。但是我想最大化我的窗口,因为让它变大是没有意义的(锚定窗格有固定的大小),只能变小。我已经弄明白了,必须设置PrimaryStage的最大大小来限制实际的窗口,限制ScrollPane没有任何作用。
问题是:如果我想为PrimayStage设置一个MaxHeight和MaxWidth,我只会得到不想要的结果。如果我想让PrimaryStage的最大尺寸和Anchorpane一样,那么这个窗口要么不显示,要么有滚动条!
如果我把这一行放在我的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();
什么也不会出现,因为显然“scrollableMainFrame”在该点没有高度。
如果我把setMaxHeight()放在末尾,比如
primaryStage.setScene(scene);
primaryStage.show();
// set max window size
primaryStage.setMaxHeight(scrollableMainFrame.getHeight());
然后,将有效地设置最大高度,但滚动条会出现并保持可见,即使窗口具有其完整大小!
有人知道为什么吗,我如何设置窗口的最大尺寸,而不总是打开滚动条?
(只需将数字添加到最大值,如primaryStage.setMaxHeight(scrollableMainFrame.getHeight() 15);
根本不做任何事情,滚动条仍然存在!)
谢谢,James_D,你引导我找到解决方案!
确实如你所说,出现了滚动条,因为PrimaryState还包含标题栏,我忘记了。这让我想:我如何根据窗口的内容计算窗口的完整大小,将其设置为最大大小?嗯,我不需要!逻辑有点扭曲,但有效:我只需要向Primary舞台询问其实际大小,并将其设置为最大值。诀窍是,我需要在创建窗口后这样做:
// create the window
primaryStage.show();
// set actual size as max
primaryStage.setMaxHeight(primaryStage.getHeight());
primaryStage.setMaxWidth(primaryStage.getWidth());