,你有兩個選擇:使用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();
1)例如
2)您可以使用JavaFx Scene Builder,這是一個JavaFx的可視化佈局工具。 例如,如果我想創建一個Hbox
佈局:
<?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();
爲什麼不能使用'StackPane','HBox'或VBox?如果你使用'Pos.CENTER',他們可以有自己的對齊設置,它將自動將兩個維度放在兩個維度上。 –
整個想法是我有一個錨定窗格,然後我希望用戶能夠添加任何佈局(VBox,HBox或Stackpane)。但是,錨定窗格的大小會發生變化並且沒有首選大小。那麼你如何將它與任何你使用的佈局集中在一起。 – darewreck
您提到的佈局選擇都可以解決上述問題。我很困惑。爲什麼你必須使用'AnchorPane'? –