[英]JavaFX scaling does not resize the component in parent container
我有一個容器需要顯示兩個自定義組件,按比例縮小 25%,使它們垂直對齊。 我正在使用從這個 FXML 加載的 VBox:
<fx:root type="VBox" fx:id="leaderDisplay" xmlns="https://javafx.com/javafx" xmlns:fx="http://javafx.com/fxml" fx:controller="MyController"
prefHeight="720.0" prefWidth="200.0" alignment="CENTER">
</fx:root>
並且組件是從此 FXML 加載的:
<fx:root stylesheets="@css/style.css" type="StackPane"
maxHeight="294.0" maxWidth="195.0"
fx:controller="MyOtherController"
xmlns="http://javafx.com/javafx/16" xmlns:fx="http://javafx.com/fxml/1">
<AnchorPane fx:id="cardPane" styleClass="leader-card" prefHeight="294.0" prefWidth="195.0">
<FlowPane fx:id="lcRequirements" layoutX="13.0" layoutY="10.0" />
<Label fx:id="lcVictoryPoints" layoutX="87.0" layoutY="162.0" prefHeight="25.0" prefWidth="20.0" text="0" />
</AnchorPane>
<Pane fx:id="cardBack" styleClass="leader-card-back" maxHeight="294.0" maxWidth="195.0" visible="false" />
</fx:root>
我使用此方法在 VBox controller 中以編程方式添加所需的組件:
private void addLeader(LeaderCard newLeader) {
Platform.runLater(() -> {
setStyle("-fx-background-color: grey;");
LeaderCardWidget newWidget = new LeaderCardWidget(newLeader);
System.out.println("Height before: " + newWidget.getMaxHeight());
newWidget.setStyle("-fx-border-color: black;" +
"-fx-border-width: 3");
newWidget.setScaleX(0.75);
newWidget.setScaleY(0.75);
System.out.println("Height after: " + newWidget.getMaxHeight());
leaderDisplay.getChildren().add(newWidget);
leadersAndWidgets.put(newLeader, newWidget);
});
}
問題是組件正在按比例縮小,但 vbox 無法正確顯示它們,在它們周圍留下巨大的間距(右側是相同的屏幕截圖,未縮放以供參考):
從布局文檔的“視覺邊界與布局邊界”部分:
Node
提供 layoutBounds 屬性來定義節點的“邏輯”邊界以進行布局,並提供 boundsInParent 來定義應用所有效果、剪輯和變換后的視覺邊界。 ...如果使用ScaleTransition
來脈沖按鈕的大小,則該脈沖 animation 不會干擾該按鈕周圍的布局。 如果應用程序希望將效果、剪輯或變換因素考慮到節點的布局中,則應將該節點包裝在Group
中。
簡而言之,諸如縮放之類的變換不會被考慮到父級的布局計算中。 您可以通過將組件包裝在一個組中來實現這一點。 我認為你可以在你的代碼中實現這一點
// leaderDisplay.getChildren().add(newWidget);
leaderDisplay.getChildren().add(new Group(newWidget));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.