【问题标题】:How to center a node within a pane javafx如何在窗格javafx中居中节点
【发布时间】:2014-06-27 20:50:32
【问题描述】:

如何创建一个窗格并将一个子 Node 放在中心?

假设Pane500 by 500NodeImageView200 by 200 Image

ImageView view = new ImageView();

Image img = new Image("test.png");
view.setImage(img);
Pane pane = new Pane();
pane.setMinWidth(500);
pane.setMinHeight(500);
pane.getChildren().add(view);

【问题讨论】:

  • 您为什么不能使用StackPaneHBoxVBox?如果您使用Pos.CENTER,他们可以设置他们的对齐方式,这将自动将他们的孩子在两个维度上居中。
  • 整个想法是我有一个锚窗格,然后我希望用户能够添加任何布局(VBox、HBox 或 Stackpane)。但是,锚窗格的大小会发生变化,并且没有首选大小。然后,您将如何以您使用的任何布局将其居中。
  • 你提到的布局选择都解决了我上面解释的问题。我很迷惑。为什么必须使用AnchorPane

标签: javafx javafx-2 center pane


【解决方案1】:

你有两个选择:

  1. 例如使用StackPane而不是Pane(因为你可以使用Pos

    StackPane p = new StackPane();
    p.setPrefSize(700,700); //set a default size for your stackpane
    Image img = new Image("test.png"); //create an image
    ImageView v = new ImageView(img); //create an imageView and pass the image 
    
    p.getChildren().add(v); //add imageView to stackPane
    StackPane.setAlignment(v,Pos.CENTER_LEFT); //set it to the Center Left(by default it's on the center)
    stage.setScene(new Scene(p));
    stage.show();
    
  2. 您可以使用JavaFx Scene Builder,它是JavaFx 的可视化布局工具。 例如,如果我想创建一个Hbox 布局:

    <?xml version="1.0" encoding="UTF-8"?>
    
        <?import java.lang.*?>
        <?import java.net.*?>
        <?import java.util.*?>
        <?import javafx.geometry.*?>
        <?import javafx.scene.*?>
        <?import javafx.scene.control.*?>
        <?import javafx.scene.effect.*?>
        <?import javafx.scene.image.*?>
        <?import javafx.scene.layout.*?>
        <?import javafx.scene.shape.*?>
        <?import javafx.scene.text.*?>
    
        <HBox alignment="CENTER" prefHeight="369.0" prefWidth="425.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" >
            <children>
                <ImageView fitHeight="150.0" fitWidth="200.0" pickOnBounds="true" preserveRatio="true" x="0.0" HBox.hgrow="NEVER">
                    <image>
                        <Image url="@../yourImg.png" />
                    </image>
                </ImageView>
            </children>
        </HBox>
    

    在你的主类中保存为myLayout.fxml,并在你的代码中添加以下内容:

    Hbox root = FXMLLoader.load(getClass().getResource("myLayout.fxml"));
    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.show();
    

【讨论】:

  • 谢谢。如果它是一个没有首选大小的 anchorPane 会发生什么。我试图将 stackPane 添加到 Anchor Pane 中。但是,如果没有设置首选尺寸,则居中将不起作用。在我的示例中,锚窗格可以调整大小,因为左、右、上和下是可以打开的选项卡,并且可以更改中心锚窗格的大小。
【解决方案2】:

我通常使用以下方法将节点/窗格居中:

<VBox alignment="CENTER">
    <HBox alignment="CENTER">
        <!-- your node/pane -->
    </HBox>
</VBox>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多