Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX without extending Application class [duplicate]

When we create a javafx application, we usually extends the Application class.

public class Myjavafx extends Application{
    public static void main(String[] args) {
        launch(args);
    }
    @Override
    public void start(Stage primaryStage){
        Button btn = new Button();
        btn.setText("click me");

        BorderPane pane = new BorderPane();
        pane.setCenter(btn);

        Scene scene = new Scene(pane, 300,250);

        primaryStage.setScene(scene);
        primaryStage.setTitle("my app");
        primaryStage.show();
    }
}

but can i do it without extending the Application class? i have tried to create javafx application without extending it.

public class Myjavafx{
    public static void main(String[] args) {
        Application myapp = new Application(){
            @Override
            public void start(Stage primaryStage){
                Button btn = new Button();
                btn.setText("click me");

                BorderPane pane = new BorderPane();
                pane.setCenter(btn);

                Scene scene = new Scene(pane, 300,250);

                primaryStage.setScene(scene);
                primaryStage.setTitle("my app");
                primaryStage.show();
            }
        };
        myapp.launch(args);
    }
}

but it turn out an error

class Myjavafxis not a subclass of javafx.application.Application

is it necessary to extends Application class?or am i doing it wrong.

like image 367
Fadhil Ahmad Avatar asked Mar 22 '26 01:03

Fadhil Ahmad


1 Answers

Note that you are already extending Application by creating an anonymous inner class. However, JavaFX requires that you extend Application from a named class. This is because launch() is a static method which creates the Application instance by reflection. The way you call launch() here hides this fact. It would be better to call Application.launch() rather than myapp.launch() since this makes it clear the launch() is static.

like image 54
Code-Apprentice Avatar answered Mar 24 '26 06:03

Code-Apprentice