gpt4 book ai didi

VBox 中的 JavaFX 中心按钮

转载 作者:行者123 更新时间:2023-12-05 06:38:15 27 4
gpt4 key购买 nike

我无法在 Java 代码中将 VBox 中的 Button 居中!我使用 Scene Builder 创建了一个 SplitPane,其中左侧的 AnchorPane 有一个位于 VBox 中心的 Button。我想重新创建这个,VBox 中的一个按钮,在正确的 AnchorPane 中,但不是在 FXML 中,在 Java 代码中。但是右边的按钮不居中,虽然我使用 vb.setAlignment(Pos.CENTER); :

enter image description here

我的 FXML 代码:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.SplitPane?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.VBox?>

<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="200.0" prefWidth="400.0" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1" fx:controller="testimageview.MainViewController">
<children>
<SplitPane dividerPositions="0.5" prefHeight="200.0" prefWidth="400.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<items>
<AnchorPane fx:id="leftAnchorPane" minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
<children>
<VBox alignment="CENTER" prefHeight="198.0" prefWidth="171.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<children>
<Button mnemonicParsing="false" text="FXML" />
</children>
</VBox>
</children>
</AnchorPane>
<AnchorPane fx:id="rightAnchorPane" minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0" />
</items>
</SplitPane>
</children>
</AnchorPane>

还有我的 Java Controller 类代码:

package testimageview;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;

public class MainViewController implements Initializable {

@FXML
private AnchorPane leftAnchorPane;

@FXML
private AnchorPane rightAnchorPane;

public MainViewController() {
}

@Override
public void initialize(URL url, ResourceBundle rb) {
VBox.setVgrow(leftAnchorPane, Priority.ALWAYS);

VBox vb = new VBox();

Button rightButton = new Button();
rightButton.setText("Java");

vb.setAlignment(Pos.CENTER);
vb.getChildren().addAll(rightButton);

rightAnchorPane.getChildren().add(vb);

}
}

最佳答案

好吧,你没有定义 VBox 的尺寸,所以默认情况下(在 ScrollPane 内)它将适合它的 child 的大小,在你的情况下,按钮大小为 50,50 或类似的东西,所以你看不到结盟。您需要做的就是定义 VBox 的大小以匹配第二个 AnchorPane 的大小,或者您可以绑定(bind)它们的尺寸(宽度、高度),例如:

vb.prefWidthProperty().bind(rightAnchorPane.widthProperty());
vb.prefHeightProperty().bind(rightAnchorPane.heightProperty());

关于VBox 中的 JavaFX 中心按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46486750/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com