为什么我使用id获得ImageView引用为null?

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

我在fxml文件中放置了一个图像,为其指定了ID,然后在相关控制器中使用该ID。但我不明白为什么它为null ??

这是我的fxml文件:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.image.Image?>
<?import javafx.scene.image.ImageView?>
<?import javafx.scene.layout.Pane?>

<Pane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.171" xmlns:fx="http://javafx.com/fxml/1" fx:controller="sample.Ball">
   <children>
         <ImageView fx:id="imageView" fitHeight="150.0" fitWidth="200.0" layoutX="153.0" layoutY="116.0" pickOnBounds="true" preserveRatio="true">
            <image>
               <Image url="@../resources/2.jpg" />
            </image>
         </ImageView>
   </children>
</Pane>

这是控制器类:

package sample;

import javafx.fxml.FXML;
import javafx.scene.image.ImageView;
import javafx.scene.input.KeyEvent;

import static javafx.scene.input.KeyCode.UP;

public class Ball {
    @FXML
    public ImageView imageView;

    public void moveBallOnKeyPress(KeyEvent e) {
        if (e.getCode().equals(UP)) {
            System.out.println(imageView);
        }
    }
}

这是我如何称呼此方法:

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {
public static Scene scene ;

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("Hello World!");
        scene = new Scene(root, 600, 550);
        Ball ball = new Ball();
        scene.setOnKeyPressed(e -> ball.moveBallOnKeyPress(e));
        primaryStage.setScene(scene);
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}

我在控制台中看到的是'null',并且在imageView上调用方法时,我得到了null指针异常

javafx fxml
1个回答
1
投票

您正在为onKeyPressed设置Scene处理程序以在您创建的Ball实例上调用方法:

Ball ball = new Ball();
scene.setOnKeyPressed(e -> ball.moveBallOnKeyPress(e));
当然,

@FXML注释的字段仅在控制器中初始化。仅仅因为它们是同一类的实例,就不会以其他方式初始化它们。您需要设置事件处理程序以引用实际的控制器:

@Override
public void start(Stage primaryStage) throws Exception{
    FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
    Parent root = loader.load();
    primaryStage.setTitle("Hello World!");
    scene = new Scene(root, 600, 550);
    Ball ball = loader.getController();
    scene.setOnKeyPressed(e -> ball.moveBallOnKeyPress(e));
    // or scene.setOnKeyPressed(ball::moveBallOnKeyPress);
    primaryStage.setScene(scene);
    primaryStage.show();
}
© www.soinside.com 2019 - 2024. All rights reserved.