How to center a node within a pane javafx

…衆ロ難τιáo~ 提交于 2019-11-29 18:22:47

问题


How do I create a Pane and have a child Node put at the center?

Lets say the Pane is 500 by 500 and the Node is an ImageView with a 200 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);

回答1:


you have 2 choices :

  1. For example using StackPane instead of Pane (because you can use 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. You can use JavaFx Scene Builder, it's a visual layout tool for JavaFx. For example if I want to create a Hbox layout:

    <?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>
    

    save-it as myLayout.fxml inside your main class and add following to your code:

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



回答2:


I usually use the following approach to center a node/pane:

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


来源:https://stackoverflow.com/questions/23576044/how-to-center-a-node-within-a-pane-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!