【发布时间】:2019-03-27 17:18:28
【问题描述】:
您好,我是 JavaFX 新手,在使用 fx:id 时遇到问题。
我的控制器类中出现空指针异常。
虽然fx:id 和控制器类中的声明匹配,但不会创建对象apple 和snake。
有人可以帮我吗?
主类:
public class Main extends Application {
private Controller controll = new Controller();
@Override
public void start(Stage primaryStage) {
try {
Parent root = FXMLLoader.load(getClass().getResource("World2.fxml"));
Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
scene.setOnKeyPressed(controll);
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
控制器类:
public class Controller implements EventHandler<Event> {
@FXML
private ImageView snake;
@FXML
private ImageView apple;
private int snakeRow = 8;
private int snakeColumn = 10;
private int appleRow = 5;
private int appleColumn = 5;
@Override
public void handle(Event ev) {
KeyEvent event = (KeyEvent) ev;
System.out.println("handle-Methode");
if (event.getCode() == KeyCode.LEFT && snakeColumn > 0) {
snakeColumn--;
System.out.println("Snake-ID: " + snake);
System.out.println("Apple-ID: " + apple);
}
}
FXML:
<ImageView fx:id="apple" fitHeight="39.0" fitWidth="44.0" pickOnBounds="true" GridPane.columnIndex="5" GridPane.rowIndex="5">
<image>
<Image url="@../img/icons8-apfel-48.png" />
</image>
</ImageView>
<ImageView fx:id="snake" fitHeight="36.0" fitWidth="44.0" pickOnBounds="true" GridPane.columnIndex="10" GridPane.rowIndex="8">
<image>
<Image url="@../img/icons8-hydra-48.png" />
</image>
</ImageView>
【问题讨论】:
标签: javafx nullpointerexception fxml