无法调用“javafx.scene.image.ImageView.setImage(javafx.scene.image.Image)”,因为“this.Image1”为空

问题描述 投票:0回答:1

我正在使用 FXML 来制作这个 JavaFX 程序,并且遇到了某些错误 我试图在按某个按钮 3 次后使图像发生变化,但是当我按该按钮 3 次时,它会给出 NullPointerException 错误以及标题的错误消息。我怀疑这是因为我的主要方法,我在其中创建了一个控制器以允许按键。

这里我使用名为 createPage 的函数初始化图像,这在初始化 FXML 页面时被调用。

int currentID = 1;
int selected = 1;
int box = currentID%3;
public void createPage() throws URISyntaxException {
        do {
            for (ImageInfo image : Database.ImgList){
                if(image.getId()==currentID){
                    changeImage(image.getName(),box);
                }
            }
            currentID++;
            box = currentID%3;
        } while (box!=1);
    }

这是主要方法,我在其中为控制器调用了一个变量,这使得可以检测按键并做出相应的反应,我相信这就是问题所在。

public void start(Stage stage) throws IOException {
        HelloController controller = new HelloController();
        Database.loadImages();
        FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("hello-view.fxml"));
        Scene scene = new Scene(fxmlLoader.load(), 676, 503);
        scene.setOnKeyPressed(controller::moveCharacter);
        stage.setTitle("For You");
        stage.setScene(scene);
        stage.show();
    }

下面的两块代码显示我尝试检测某个按键的按下情况,按下该键三次后,图像会发生变化。

public void moveCharacter(KeyEvent event) {
        switch (event.getCode()){
            case D, RIGHT:
                try {
                    moveForward();
                } catch (URISyntaxException e) {
                    throw new RuntimeException(e);
                }
private void moveForward() throws URISyntaxException {
        if (selected%3==0){
            createPage();
        } else {
            selected++;
        }
    }

遇到这个问题时,我尝试检查使用 .setImage 函数是否不允许我覆盖图像。事实证明并非如此。

我还检查了这两个函数的变量 currentID。这时我意识到在 moveForward 函数中,currentID 再次变为 1。所以这让我相信发生了某些事情,从而将所有图像变为空。

我尝试了各种解决方案,例如更改允许检测按键的方式,但没有效果。

java javafx controller imageview fxml
1个回答
0
投票

您的问题中没有足够的信息来确定这里发生了什么,但听起来

HelloController
是您的
hello-view.fxml
中指定的控制器类,它有一个带有
fx:id="image1"
的元素被注入通过
@FXML
注释来控制控制器。

假设所有这些都是正确的,

image1
字段只会在实际控制器中初始化,它是加载和解析FXML文件时由
FXMLLoader
为您创建的对象。其他对象中的
image1
字段会以某种方式初始化,仅仅因为它们与实际控制器属于同一类,这并不奇怪。

在场景中注册事件处理程序时需要指定实际的控制器实例,即

public void start(Stage stage) throws IOException {
    Database.loadImages();
    FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("hello-view.fxml"));
    Scene scene = new Scene(fxmlLoader.load(), 676, 503);

    HelloController controller = fxmlLoader.getController();

    scene.setOnKeyPressed(controller::moveCharacter);
    stage.setTitle("For You");
    stage.setScene(scene);
    stage.show();
}
© www.soinside.com 2019 - 2024. All rights reserved.