首页 > 解决方案 > JAVAFX - 如何在启动应用程序时调用方法

问题描述

我是 JavaFX 的新手。但我真的很想学习。我知道如何使用 ActionEvent 调用方法,但是如果我有一个方法,我想在启动应用程序后立即调用呢?通常,这些方法只会在您执行操作(例如按下按钮)时执行,但在这种情况下,我只想在启动时运行它。有人可以帮忙吗?

标签: javajavafxmethodsscenebuilder

解决方案


只需在应用程序的方法中调用您要调用的start方法即可。

public class Main extends Application {

    @Override
    public void init() {
        //you can call your method here but if you 
        //plan on doing stuff to the stage call it in the start method
    }

    @Override
    public void start(Stage stage) throws Exception {
        // call your method here
        myMethod();

        //show the application
        BorderPane pane = new BorderPane();
        Scene scene = new Scene(pane);
        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }


    public void myMethod() {
        //do Stuff
    }
}

您可以在方法内部调用该方法,init()但不能对舞台或场景做任何事情。


推荐阅读