java - 调整窗口大小时在场景中居中滚动窗格
问题描述
嗨,我有一个带有 GridPane 的 ScrollPane,因为它是孩子,
ScrollPane scroll = new ScrollPane(grid);
Scene scene = new Scene(scroll);
有谁知道如何在调整窗口大小时使 ScrollPane 的项目在场景中居中?
解决方案
ScrollPane
如果我正确理解了这个问题,当内容小于视口时,您希望将内容居中。这并不像简单地使用将其子元素作为内容居中的布局那样简单。AScrollPane
默认情况下,仅将其内容调整为所述内容的首选大小,但将内容与左上角对齐。这意味着当内容小于视口时,只占用左上角的空间;即使内容以自己的孩子为中心,内容的面积也不等于视口的面积,因此内容不在视口内居中。
ScrollPane
如果有一个“对齐”属性来自定义这种行为,那就太好了。由于不存在这样的属性,您必须配置ScrollPane
以填充其视口,同时还允许内容超出视口的尺寸。然后,您只需要使用一个将其子元素居中的布局,或者可以配置为这样做——<code>GridPane 就是这样一种布局。这是一个例子:
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Region;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
// create and populate GridPane
GridPane gridPane = new GridPane();
gridPane.setHgap(10);
gridPane.setVgap(10);
for (int row = 0; row < 10; row++) {
for (int col = 0; col < 10; col++) {
Rectangle rectangle = new Rectangle(50, 50, Color.TRANSPARENT);
rectangle.setStroke(Color.BLACK);
gridPane.add(rectangle, col, row);
}
}
/*
* From the property's Javadoc: "The alignment of the grid within
* the gridpane's width and height".
*
* Using Pos.CENTER makes the GridPane center its grid when the GridPane
* has extra horizontal and/or vertical space.
*/
gridPane.setAlignment(Pos.CENTER);
/*
* Forces the dimensions of the GridPane to be at least the same
* as its preferred size. This prevents the GridPane from shrinking
* due to the fit-to-width/fit-to-height configuration of the
* ScrollPane.
*/
gridPane.setMinSize(Region.USE_PREF_SIZE, Region.USE_PREF_SIZE);
ScrollPane scrollPane = new ScrollPane(gridPane);
/*
* Forces the content of the ScrollPane to have the same dimensions
* as the viewport. However, because of the min-size configuration above,
* the GridPane can never be smaller than its preferred size. This means
* the ScrollPane will grow its content to fit the viewport but won't
* shrink its content to fit the viewport.
*/
scrollPane.setFitToWidth(true);
scrollPane.setFitToHeight(true);
primaryStage.setScene(new Scene(scrollPane, 600, 400));
primaryStage.show();
}
}
请注意,根据您的用例,您可能不需要将内容的最小大小配置为与其首选大小相同。
推荐阅读
- node.js - Node.js 项目设置方法有问题
- python - Numpy ndarray 形状参数
- javascript - 如何从 JS 访问 HTML 中的 var?
- react-testing-library - 网络错误错误:在反应测试库中进行一定数量的测试后连接 ECONNREFUSED 127.0.0.1:5000
- angular - Angular/Ionic - Ngrx - 更新数组中的对象
- r - 如何使用 purrr::possively 捕获绘图错误
- python - 我的 PyQt5 脚本在函数内跳过了一行
- javascript - 如何在python中实现嵌套增量循环
- class - 潜在类别分析
- php - 表单标签自动关闭(无父关闭)