JavaFX fx:id在控制器类中未创建对象

时间:2018-10-23 12:51:01

标签: javafx nullpointerexception fxml

您好,我是JavaFX的新手,并且fx:id遇到了问题。

我的控制器类中出现一个空指针异常。

尽管apple和控制器类中的声明匹配,但未创建对象snakefx:id

有人可以帮我吗?

主要类别:

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>

1 个答案:

答案 0 :(得分:2)

除非某个控制器实例与场景不关联,否则

  1. 它由FXMLLoader根据fxml中的fx:controller属性创建。在这种情况下,您需要从FXMLLoader实例中检索控制器实例,该实例用于在加载后加载fxml:

    FXMLLoader loader = new FXMLLoader(getClass().getResource("World2.fxml"));
    Parent root = loader.load();
    Controller controll = loader.getController();
    

  2. 您无需指定fx:controller属性,而是在加载用作场景控制器的Object之前将FXMLLoader传递给FXMLLoader loader = new FXMLLoader(getClass().getResource("World2.fxml")); loader.setController(controll); Parent root = loader.load();

    dropdown-toggle