Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run method from controller class on startup Javafx

I got a javafx application and I got a main where I set up my stage and launch the application. I also have a controller class:

public class Controller
{    
    @FXML Button button;
    public void test(){
        button.setText("Button");
    }
}

How would I go about running the test method on startup. I know I can create an instance in the main class...

public class Main extends Application{
   public void start(Stage primaryStage) throws Exception {
      ...

   public static void main (String[] args){
        launch (Main.class);
        Controller cont = Controller();
        cont.test();
   }
}

and that would work. However it is not ideal for me. I was wondering if it was possible to run the method directly from the controller class, if not is there a better way of handling this? Thanks

like image 719
Cornelius Avatar asked Dec 05 '22 19:12

Cornelius


1 Answers

The initialize() method is called automatically when the FXML is loaded:

public class Controller
{    
    @FXML Button button;
    public void initialize(){
        button.setText("Button");
    }
}

Note that your code in the Main class won't work at all. First, launch() does not exit until you exit the application, and second, you are calling it on a new instance of the controller, not the one that is connected to the UI you load from the FXML file.

like image 194
James_D Avatar answered Jan 19 '23 10:01

James_D