0

I'm new when it comes to JavaFX. But I really wanna learn. I'm I know how to call methods using ActionEvent, but what if I have a method that I want to call as soon as I launch the application? Normally the methods only get executed, when you perform an action, like pressing a button, but in this case I just want to run it along with the startup. Could anyone help here?

1 Answers1

2

Just call the method you want to call in the start method of your application.

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
    }
}

You can call the method inside the init() method but you can't do stuff to the stage or scene.

fabian
  • 80,457
  • 12
  • 86
  • 114
IbzDawg
  • 79
  • 7
  • What if the method, that I'm trying to use is located in the Controller class? – Lukas Méndez Duus Nov 25 '18 at 20:53
  • 2
    You can call the method inside the initialize method of the controller. The initialize method is called when the FXML file is loaded. – IbzDawg Nov 25 '18 at 21:00
  • 1
    @LukasMéndezDuus There's a question about that topic: https://stackoverflow.com/questions/14187963/passing-parameters-javafx-fxml – fabian Nov 25 '18 at 21:45