【问题标题】:Set responsive layout with JavaFX使用 JavaFX 设置响应式布局
【发布时间】:2017-01-11 11:12:43
【问题描述】:
我开始使用 javaFX,我想设置这样的布局:
我安装了场景构建器,但没有选项可以使用像 html 中的简单 div 这样的百分比...
那么设置此布局的最佳选择是什么?
它是我的简单 fxml 文件:(现在它是空的)
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane xmlns:fx="http://javafx.com/fxml/1">
<!-- TODO Add Nodes -->
</AnchorPane>
很多
【问题讨论】:
标签:
java
layout
javafx
responsive
【解决方案1】:
您可以通过使用带有适当约束的GridPane 来实现这种布局:
@Override
public void start(Stage primaryStage) throws IOException {
GridPane root = new GridPane();
root.getColumnConstraints().addAll(DoubleStream.of(30, 2, 68)
.mapToObj(width -> {
ColumnConstraints constraints = new ColumnConstraints();
constraints.setPercentWidth(width);
constraints.setFillWidth(true);
return constraints;
}).toArray(ColumnConstraints[]::new));
RowConstraints rowConstraints = new RowConstraints();
rowConstraints.setVgrow(Priority.ALWAYS);
root.getRowConstraints().add(rowConstraints);
root.addRow(0, Stream.of("red", "green", "blue").map(s -> {
Region region = new Region();
region.setStyle("-fx-background-color:"+s);
return region;
}).toArray(Node[]::new));
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}
FXML 版本
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<GridPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
<columnConstraints>
<ColumnConstraints percentWidth="30.0" />
<ColumnConstraints percentWidth="2.0" />
<ColumnConstraints percentWidth="68.0" />
</columnConstraints>
<rowConstraints>
<RowConstraints vgrow="ALWAYS" />
</rowConstraints>
<children>
<Region style="-fx-background-color: red;" />
<Region style="-fx-background-color: green;" GridPane.columnIndex="1" />
<Region style="-fx-background-color: blue;" GridPane.columnIndex="2" />
</children>
</GridPane>
【解决方案2】:
我在以下主题中为此创建了一个答案:How do specify a width percentage in JavaFX 2 using FXML?
下面是那些懒得去那里的人的副本;-)
为了开始使用 FXML 本身的百分比,您可以使用以下内容:
<fx:define>
<Screen fx:factory="getPrimary" fx:id="screen" />
</fx:define>
这将帮助您检测当前屏幕的尺寸,即正在显示应用程序。现在我们有了显示尺寸,我们可以在 FXML 中使用它,如下所示:
<HBox fx:id="hroot" prefHeight="${screen.visualBounds.height}" prefWidth="${screen.visualBounds.width}"> Your FXML elements inside the root... </HBox>
请注意,我使用 visualBounds,因为这样可以让我获得屏幕上的可用空间,例如,我不希望与 Windows 中的任务栏重叠。对于全屏应用程序,您只需使用“边界”。
现在,为了使用百分比,您实际上可以使用 prefheight 和 prefWidth 的值。您可以将计算放在 ${} 中。
可选:
如果您想让所有元素都使用相对大小,只需引用它们,使用它们的 ID 和 width 或 height 属性,然后进行计算。
<VBox fx:id="VBSidebar" prefWidth="${hroot.width*0.15}" prefHeight="${hroot.height}"> more elements.. </VBox>