代码之家  ›  专栏  ›  技术社区  ›  Zhe Hin Yap

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

  •  0
  • Zhe Hin Yap  · 技术社区  · 2 年前

    我正在使用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。所以这让我相信发生了什么事情,把所有的图像都变成了空。

    我尝试过各种解决方案,比如改变允许检测按键的方式,但都无济于事。

    1 回复  |  直到 2 年前
        1
  •  2
  •   James_D    2 年前

    你的问题中没有足够的信息来确定这里发生了什么,但听起来 HelloController 是在中指定的控制器类 hello-view.fxml ,具有一个元素 fx:id="image1" 其通过 @FXML 注释。

    假设所有这些都是真的 image1 字段将仅在实际控制器中初始化,实际控制器是由 FXMLLoader 当加载和解析FXML文件时。没有什么奇怪的魔法可以让 图像1 其他对象中的字段将以某种方式初始化,因为它们与实际控制器属于同一类。

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

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