本文介绍了如何在窗格javafx中居中节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何创建一个窗格并让一个孩子节点
放在中心?
How do I create a Pane and have a child Node
put at the center?
让我们说 Pane
500
按 500
和节点
是 ImageView
, 200
按 200
图像
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);
推荐答案
您有2个选择:
-
例如使用
StackPane
代替Pane
(因为你可以使用)
For example using
StackPane
instead ofPane
(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();
您可以使用 JavaFx Scene Builder ,它是一个可视化的布局JavaFx的工具。
例如,如果我想创建一个 Hbox
布局:
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>
将其保存为 myLayout.fxml
里面您的主类并在代码中添加以下内容:
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();
这篇关于如何在窗格javafx中居中节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!