java - 使用 SceneBuilder 显示图像

标签 java javafx scenebuilder

我使用 SceneBuilder、3 个按钮和 2 个 ImageView 创建了一个小型 FXML 文件。

我想做的是:

  1. 运行应用并在启动时显示 2 张图像
  2. NEXT按钮时,显示另外2张图像。

我的问题不是切换图像,而是将图像显示为场景生成器创建的 ImageView。

这是我的 Controller 类:

public class Controller {
    private Button Next; //1st button
    private Button J2inc; //2nd button
    private Button J1inc; /3rd button
    private ImageView Img1;
    private ImageView Img2;

    void Inc2(ActionEvent event) {
        //nothing for the moment
    }
    void Inc1(ActionEvent event) {
        //nothing for the moment
    }
    void Nextimg(ActionEvent event) {
        //nothing for the moment
    }
}

还有我的start方法:

public void start(Stage primaryStage) throws Exception {
    Parent root =  FXMLLoader.load(getClass().getResource("Css.fxml"));
    Scene scene = new Scene(root);
    primaryStage.setScene(scene);
    primaryStage.setTitle("P ");
    primaryStage.show();
}

我不知道如何初始化 ImageView img1 所以它会加载一些东西。

无法在此处添加 FXML,因此我只添加 ImageView 行:

  <ImageView fx:id="Img1" fitHeight="750.0" fitWidth="450.0" layoutY="22.0" pickOnBounds="true" preserveRatio="true" AnchorPane.bottomAnchor="50.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="450.0" AnchorPane.topAnchor="25.0" />

最佳答案

要在 Controller 中初始化它,请通过注释 @FXML 使其可访问,并在 Controller 的 initialize() 方法中初始化它:

public class Controller {
    private Button Next; //1st button
    private Button J2inc; //2nd button
    private Button J1inc; /3rd button

    @FXML
    private ImageView Img1;

    private ImageView Img2;

    public void initialize() {
        Img1.setImage(new Image(...));
    }

    void Inc2(ActionEvent event) {
        //nothing for the moment
    }

    void Inc1(ActionEvent event) {
        //nothing for the moment
    }

    void Nextimg(ActionEvent event) {
        //nothing for the moment
    }
}

如果您希望直接在 FXML 中对其进行初始化,请为 image 属性提供一个值。在场景生成器中,您可以选择 ImageView 并在右上角的“图像”字段(“属性”下)中输入图像的 URL。请务必阅读Image documentation了解如何解释 URL 的字符串表示形式。

关于java - 使用 SceneBuilder 显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42558641/

相关文章:

java - 我想在执行点击事件时获取GridPane的索引

Javafx场景生成器: Handling Multiple mouseClick() events from different source objects

java - 以编程方式更改 LinearLayout 的背景颜色

java - 编译时错误 - 在 import java.io.BufferedReader 中找不到符号;

Java - 应用程序在 Thread.sleep 方法上崩溃

java - 没有 Maven 的 Vaadin Clojure 小部件编译

css - JavaFX - 样式化未聚焦的 ListView 行

javafx-2 - 如何在 Controller 类中的 JavaFX 应用程序中交换屏幕?

java - 如何添加新玩家?

javafx-8 - 一段时间后无法打开 FXML