【发布时间】:2020-05-26 18:38:25
【问题描述】:
我在我的 fxml 文件中放了一个图像,给它一个 id,然后在相关控制器中使用该 id。 但我不明白为什么它是空的??
这是我的 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 上调用方法我得到空指针异常
【问题讨论】:
-
@James_D 我使它成为非静态的,但问题仍然存在。我真的不知道怎么了,我糊涂得要死:(
-
您从哪里调用该方法?您的 FXML 文件中没有将事件处理程序设置为
moveBallOnKeyPress的元素。 -
我为我的场景 setOnKeyPressed 并为事件处理程序调用此方法
-
发布代码。您实际上是如何在控制器实例上调用它的?
-
你没有在控制器上调用
moveBallOnKeyPress。您在创建的对象上调用它。图像视图不会在对象中神奇地初始化 - 它只是在控制器中初始化。