[英]How to initialize JavaFX application dynamically, not hardcoded?
在許多示例中,它展示了如何擴展Application
方法以組成和運行JavaFX應用程序。
但如果我不想怎么辦? 如果我想從我的代碼動態配置應用程序怎么辦? 示例如下:
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?
}
}
請不要就我為何需要它提出異議。
UPDATE
好的, launch()
永遠不會終止,我沒有檢查過。 無論如何,我需要有一種方法以編程方式構建應用程序,而無需任何硬編碼。
更新2
我希望從Spring構建應用程序,我現在找到了以下解決方案。
JavaFX包裝類
它將上下文初始化包裝到FX線程中,並捕獲可從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();
}
}
春天的方式建設
這里是春天建築的一個例子。 每個組件都是一個bean並在適當的位置創建:
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);
}
}
我不確定它是否會起作用,但您可以嘗試在內部類中為應用程序的參數添加setter方法,並嘗試從外部調用它們(例如從主體中調用它們)。 同樣,我不知道這是否會起作用,但我會在你的位置嘗試一下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.