. Advertisement .
..3..
. Advertisement .
..4..
I get this message: exception in thread “javafx application thread” java.lang.nullpointerexception in my JavaFX program.
This is my code:
package application;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.input.KeyEvent;
public class Main extends Application {
@Override
public void start(Stage stage) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("Scene.fxml"));
Parent root = loader.load();
Controller controller = loader.getController();
Scene scene = new Scene(root);
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent event) {
//System.out.println(event.getCode());
//if I write -> if(controller != null) it doesn't work
switch(event.getCode()) {
case UP:
controller.moveUp();
break;
case DOWN:
controller.moveDown();
break;
case LEFT:
controller.moveLeft();
break;
case RIGHT:
controller.moveRight();
break;
default:
break;
}
}
});
stage.setScene(scene);
stage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
And controller:
package application;
public class Controller {
public void moveUp() {
System.out.println("UP");
}
public void moveDown() {
System.out.println("DOWN");
}
public void moveLeft() {
System.out.println("LEFT");
}
public void moveRight() {
System.out.println("RIGHT");
}
}
If you are aware of the solution. Help me, please.
The cause: We can see the clear reason that the exception indicates: because “this.val$controller” is null. That why the message error: exception in thread “javafx application thread” java.lang.Nullpointerexception appears.
Solution:
The controller can be adjusted in one of two ways:
Before using the
load
command, explicitly executesetController
on the fxml loader instance.Or:
Set the FXML’s
fx:controller
attribute.