简体   繁体   中英

JavaFX, New window won't run

I found this piece of code, but it won't run a new blank window and keep getting NullPointerException error. ps I'm new to programming. Any help would be appreciated thanks.

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        BorderPane root = new BorderPane();

        try {

            Scene scene = new Scene(root,640,480);
            scene.getStylesheets().add(getClass().getResource("/application.css").toExternalForm());
            primaryStage.setScene(scene);
            primaryStage.show();

        } catch(Exception e) {
            e.printStackTrace();
        }

        root.setCenter(new RootLayout());
    }
    public static void main(String[] args) {
        launch(args);
    }
}

I had the same common problem when I started with JavaFX but I can explain It, It throws null pointer exception because it is not able to find your CSS file from the specified location.

I've found that you are getting nullpointer exception at the below line, scene.getStylesheets().add(getClass().getResource("/application.css").toExternalForm());

There is also another way to add your CSS file to scene

1) scene.getStylesheets().add("application.css");

2) scene.getStylesheets().add(this.getClass().getResource("/application.css").toString());

3) Package should be inside src directory and css also should be in src directory.
scene.getStylesheets().add(<packageName>.<ClassName>.class.getResource("/application.css").toExtern‌​alForm());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM