【问题标题】:Display an image with SceneBuilder使用 SceneBuilder 显示图像
【发布时间】:2017-07-22 08:51:17
【问题描述】:

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

我想做的是:

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

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

这是我的控制器类:

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" />

【问题讨论】:

  • “添加 FXML 失败”是什么意思?如果您需要知道如何格式化代码,请阅读this。另请注意,如果您使用proper naming conventions,它将帮助人们阅读您的 Java 代码(并且会正确突出显示)。
  • 是的,我就是这个意思,我会再读一遍。

标签: java javafx scenebuilder


【解决方案1】:

要在控制器中对其进行初始化,请通过注解@FXML 使变量可访问,并在控制器的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 属性提供一个值。在 Scene Builder 中,您可以选择 ImageView 并在右上角的“图像”字段中(在“属性”下)键入图像的 URL。请务必阅读Image documentation,了解如何解释 URL 的字符串表示。

【讨论】:

  • @Bouji 如果它是您问题的解决方案,您应该检查答案是否正确。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-05
  • 2023-03-13
  • 1970-01-01
  • 1970-01-01
  • 2017-11-24
  • 2012-11-07
  • 2015-11-21
相关资源
最近更新 更多