Lolitta
Lolitta

Reputation: 79

How to launch the javafx app from java code

From my java class, I used the

Chart.main(args) 

to start my javafx class with arguments. The problem that the program is blocked in javafx class and cannot return to my java class.

With

Chart.launch(args); 

I get ERROR:

java.lang.runtimeException: Error: class Image is not a subclass of javafx.application.Application.

I have found similar example to start javafx from java but without arguments.

javafx.application.Application.launch(Chart.class);

Thank you for your Help.

Upvotes: 1

Views: 755

Answers (2)

shadow
shadow

Reputation: 264

here is an example, your java code would be:

public class FXLauncher {
    public static void main(String[] args) {
        FXApplication application = new FXApplication();
        application.handleArgs(args);
        new Thread(application ).start();
    }
}

and your JavaFx application would be the following:

import javafx.application.Application;
import javafx.stage.Stage;

public class FXApplication extends Application implements Runnable  {

    public void handleArgs(String[] args){
        // handle java args
        System.out.println(args);
    }        

    @Override
    public void start(Stage stage) throws Exception {
        // your javafx code
    }

    @Override
    public void run(){
        launch();
    }   
}

Upvotes: 0

James_D
James_D

Reputation: 209694

The launch() method taking a Class parameter also takes a list of arguments, so you can do

Application.launch(Chart.class, args);

Note though that it is the launch() method that blocks until the JavaFX application exits. So, depending on exactly what you are trying to do, you might need to call this from a background thread, e.g.

new Thread(() -> Application.launch(Chart.class, args)).start();

Upvotes: 3

Related Questions