我想将StackPane作为我的根窗格。我想在场景中间有一个scrollPane作为一个小框,并在容器的下方两个按钮。
我试图通过编写以下代码来实现这一目标:
private StackPane root = new StackPane();
private Scene scene = new Scene(root, 1366, 768);
public ContinueScreen() {
Button button1 = new ButtonBuilder("My Button1").setPrefWidth(200).build();
Button button2 = new ButtonBuilder("My Button2").setPrefWidth(200).build();
Button button3 = new ButtonBuilder("My Button3").setPrefWidth(200).build();
Button button4 = new ButtonBuilder("My Button4").setPrefWidth(200).build();
Button button5 = new ButtonBuilder("My Button5").setPrefWidth(200).build();
Button button6 = new ButtonBuilder("My Button6").setPrefWidth(200).build();
VBox vBox = new VBox(5);
vBox.getChildren().addAll(button1, button2, button3, button4, button5, button6);
ScrollPane scrollPane = new ScrollPane();
scrollPane.setContent(vBox);
scrollPane.setPannable(true);
scrollPane.setMaxSize(500, 180);
scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);
scrollPane.setHbarPolicy(ScrollPane.ScrollBarPolicy.AS_NEEDED);
root.getChildren().add(scrollPane);
StackPane.setAlignment(scrollPane, Pos.CENTER);
}
您可能会注意到,代码确实可以正常工作,但是直到我添加了下面要讨论的按钮。我在HBox中将这些按钮添加为
HBox hBox = new HBox(5);
hBox.setAlignment(Pos.BOTTOM_CENTER);
hBox.getChildren().addAll(new Button("cat"), new Button("dog"));
root.getChildren().addAll(hBox);
现在同时显示滚动窗格和两个按钮。但是,滚动窗格现在由于某种原因停止工作。显示了滚动窗格及其内容,但是水平或垂直滚动条都无法使用。有谁知道为什么会这样以及如何解决?
答案 0 :(得分:2)
当您以StackPane作为根节点时,它会相互堆叠节点,因此顶部窗格是HBox,而不是ScrollPane,因此您将无法使用它。
使用BorderPane或VBox尝试。
BorderPane root = new BorderPane();
Scene scene = new Scene(root, 1366, 768);
root.setCenter(scrollPane);
HBox hBox = new HBox(5);
hBox.getChildren().addAll(new Button("cat"), new Button("dog"));
root.setBottom(hBox);
答案 1 :(得分:2)
这里的问题是允许StackPane
来调整HBox
的大小。 HBox
涵盖了防止鼠标事件到达ScrollPane
的完整场景。您可以通过为HBox
上色来轻松查看此内容:
hBox.setStyle("-fx-background-color: rgba(100%, 0%, 0%, 0.5)");
最简单的解决方案是将HBox
设置为仅在非(完全)透明区域接收事件:
hBox.setPickOnBounds(false);
不过,您也可以设置HBox
来占用所需内容的空间,以适合内容的首选大小,并通过StackPane
进行对齐:
hBox.setPrefSize(Region.USE_COMPUTED_SIZE, Region.USE_COMPUTED_SIZE);
hBox.setMaxSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE);
StackPane.setAlignment(hBox, Pos.BOTTOM_CENTER);
// hBox.setAlignment(Pos.BOTTOM_CENTER);
请注意,像这样使用StackPane
并不能为您提供响应式GUI:如果将窗口调整为足够小的高度,则按钮将覆盖ScrollPane
。
使用BorderPane
或将StackPane
和HBox
包裹在VBox
中并将VBox.vgrow
设置为Priority.ALWAYS
可能会更好StackPane
...