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);
you have 2 choices :
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();
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();