In many samples it is shown how to extend Application
method to have JavaFX app composed and ran.
But what if I don't want to? What if I want to configure app dynamically from my code? Example is below:
import javafx.application.Application;
import javafx.stage.Stage;
public class HollowTry {
public static class HollowApplication extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
}
}
public static void main(String[] args) {
Application.launch(HollowApplication.class, args);
// now I want to set title, scene etc... how?
}
}
Please don't dispute on why I need it.
UPDATE
Okay, launch()
is never terminated, I didn't check this. Anyway, I need to have a way to build application programmatically, without any hardcoding.
UPDATE 2
I was wishing con build application from Spring and I found the following solution for now.
JavaFX wrapper class
It wraps context initialization into FX thread and captures config classes to be accessible from start()
:
public class SpringJavaFX extends Application {
private static Class<?>[] annotatedClasses;
@Override
public void start(Stage primaryStage) throws Exception {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(annotatedClasses);
String title = (String) context.getBean("primaryStageTitle");
primaryStage.setTitle(title);
Scene scene = (Scene) context.getBean("primaryStageScene");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void launch(Class<?>... annotatedClasses) {
SpringJavaFX.annotatedClasses = annotatedClasses;
Application.launch();
}
}
Spring way building
And here is an example of spring-way building. Each component is a bean and created in place:
public class Attempt01_HelloWorld {
@Configuration
public static class Config {
@Bean
String primaryStageTitle() {
return "Attempt01_HelloWorld";
}
@Bean
Scene primaryStageScene() {
Scene ans = new Scene(root(), 800, 600);
return ans;
}
@Bean
Button button() {
Button ans = new Button();
ans.setText("Say 'Hello World'");
ans.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});
root().getChildren().add(ans);
return ans;
}
@Bean
StackPane root() {
StackPane root = new StackPane();
return root;
}
}
public static void main(String[] args) {
SpringJavaFX.launch(Config.class);
}
}