4

我正在使用场景生成器来创建我的 GUI,Image当用户在列表中选择项目时,我正在显示 s。Images 的大小不同,当 s小于Image它所在的窗格时,图像显示在窗格的左上角。如何让ImageView和/或Image显示在 的中心Pane

我查看了整个 javafx imageview 和 image API,但我没有发现太多关于ImageViewPane. 我也没有在场景构建器中看到任何东西。通常在场景构建器中,如果有一种方法可以使节点居中,则会有一个居中选项。

4

3 回答 3

12

在任何类型的窗格中,现在都可以在特定位置设置图像对齐.. 为此,您可以使用 tryHBox

当您将 插入 时ImageHBox最初如下所示。

截屏

现在设置对齐属性HBox

截屏

现在将对齐更改为中心并查看输出

截屏

我希望它对你有用

Pane也可以通过获取图像以编程方式执行此操作

尝试这个

AnchorPane anchorPane = new AnchorPane();
Image img = new Image(getClass().getResourceAsStream("Edit-Male-User-icon.png"));
ImageView imageView = new ImageView(img);
anch.getChildren().add(imageView );
ImageView app = (ImageView) (Node) anchorPane.getChildren().get(0);
app.setX(100);
app.setY(100);
于 2013-11-16T05:05:20.237 回答
7

在你的 start 方法中创建一个Groupand 场景:

Group root = new Group();
Scene scene = new Scene(root, 551, 400, Color.BLACK);
primaryStage.setScene(scene);

创建ImageView并设置以下属性:

ImageView imageView = new ImageView();
// set aspect ratio
imageView.setPreserveRatio(true);
// resize based on the scene
imageView.fitWidthProperty().bind(scene.widthProperty());
imageView.fitHeightProperty().bind(scene.heightProperty());

创建一个StackPane(至少这是我使用的)并绑定您的属性:

StackPane stack = new StackPane();
stack.getChildren().add(imageView);

    stack.translateXProperty()
            .bind(scene.widthProperty().subtract(stack.widthProperty())
                    .divide(2));

    stack.translateYProperty()
            .bind(scene.heightProperty().subtract(stack.heightProperty())
                    .divide(2));

将此堆栈添加到根元素:

root.getChildren().add(stack);

primaryStage在 start 方法中显示并执行其他代码:

primaryStage.show();
于 2014-09-01T07:51:47.510 回答
2

使小图像动态居中的简单方法:

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class CenterInStage extends Application {

    private final String TITLE = "Center in Stage";
    private final double WIDTH = 350;
    private final double HEIGHT = 250;
    private final String IMAGE_PATH =
            "http://icons.iconarchive.com/icons/iconka/meow-2/64/cat-rascal-icon.png";

    @Override
    public void start(Stage primaryStage) {

        primaryStage.setTitle(TITLE);

        Image image = new Image(IMAGE_PATH);
        ImageView imageView = new ImageView(image);
        imageView.setPreserveRatio(true);

        StackPane pane = new StackPane();
        pane.getChildren().add(imageView);
        StackPane.setAlignment(imageView, Pos.CENTER);

        Scene scene = new Scene(pane, WIDTH, HEIGHT);

        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

在此处输入图像描述

于 2017-04-21T08:33:45.887 回答