Mazzone
Mazzone

Reputation: 308

Trying to load FXML file to custom-made JavaFX Game class (made by professor)

I'm beyond confused, and I have no idea where to even begin with this project and it's due tomorrow. We went over literally one slide of JavaFX and they assign us a project - make an entire game, Breakout or Space Invader. I wish I was exaggerating.

Here's my current problem: I'm trying to use an FXML file in my Driver class but the Game class he provided us doesn't extend Pane, which is the only way I know to get an FXML resource.

Here's some of the code:

public class Driver extends Application {

@Override
public void start(Stage primaryStage) throws Exception {
    Game game = new Breakout(primaryStage);

    try {
        game = FXMLLoader.load(getClass().getResource("BreakoutFXML.fxml"));
    } catch (IOException e) {
        System.out.println(e);
        System.exit(1);
    } // try

    primaryStage.setTitle(game.getTitle());
    primaryStage.setScene(game.getScene());
    primaryStage.show();
    game.run();
} // start  

I get this run-time error:

Caused by: java.lang.ClassCastException: javafx.scene.layout.Pane cannot be cast to com.michaelcotterell.game.Game
    at cs1302.fxgame.Driver.start(Driver.java:19)  

Means (I think) that I can't use this method of acquiring an FXML file, so what am I supposed to do?
Here's the link to his documentation for the Game class, should be helpful.

I realize this question has been asked a lot, but I haven't been able to find anything using anything other than the standard Pane/Scene classes to get the FXML file. If it's an easy fix - awesome! Sorry for being such a noob.

Upvotes: 0

Views: 189

Answers (1)

Uluk Biy
Uluk Biy

Reputation: 49205

Well try one of these:

Pane myPane = FXMLLoader.load(getClass().getResource("BreakoutFXML.fxml"));

// 1
game.getScene().getRoot().add(myPane);
// 2
game.getScene().setRoot(myPane);
// 3
game.getStage().setScene(new Scene(myPane));

Upvotes: 2

Related Questions