如何将图像视图置于锚窗格中心?

时间:2013-11-16 04:45:13

标签: java user-interface imageview javafx scenebuilder

我正在使用场景构建器来创建我的GUI,并且当用户选择列表中的项目时,我正在显示ImageImage具有不同的大小,当Image小于其所在的窗格时,图像显示在窗格的左上角。如何让ImageView和/或Image显示在Pane的中心?

我在整个javafx imageview和图片API中都看了一下,但我没有找到将ImageView集中在Pane的内容。我也没有在场景构建器中看到任何东西。通常在场景构建器中,如果有一种方法可以使节点居中,则会有一个居中选项。

3 个答案:

答案 0 :(得分:10)

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

当您将Image插入HBox时,最初显示如下所示。

screenshot

现在设置HBox

的对齐属性

screenshot

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

screenshot

我希望它为你工作

也可以通过获取图像<{1}}以编程方式执行此操作

试试这个

Pane

答案 1 :(得分:6)

在start方法中创建Group和场景:

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();

答案 2 :(得分:3)

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

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);
    }
}

enter image description here