JavaFX运行时会创建多个线程处理程序,不同线程在程序的不同阶段处理不同任务。JavaFX在程序运行阶段主要有以下四个方法:
The no-args constructor
The init() method
The start() method
The stop() method
创建顺序依次。
有两个线程:
JavaFX-Launcher和JavaFX Application Thread分别处理以上方法,其中init()方法由JavaFX-Launcher线程创建,其余三个方法由JavaFX Application Thread。The no-args constructor用来创建继承Application的子类的实例,是JavaFX的主程序,第一个创建;随后调用init()方法,加载程序运行中需要的各项资源,init()方法不可用来创建Stage或Scene的实例(实测创建Stage实例会导致抛出异常,Scene不会),如创建则会抛出异常;start()方法用来创建Stage和Scene,并将其显示给用户;stop()方法在结束程序是调用,在Application此方法体为空,程序员可以override此方法。
以下是测试代码,验证以上四个方法的调用情况。
public class FXLifeCycleApp extends Application {
public FXLifeCycleApp() {
String name = Thread.currentThread().getName();
System.out.println("no-args Custructor : " + name);
stageInClass = new Stage();
//在init方法中create Scene或Stage都会导致报错
Scene scene = new Scene(new Group(), 300, 200);
Stage stage = new Stage();
stage.setScene(scene);
stage.setTitle("no-args constructor");
stage.show();
//Platform.setImplicitExit(false);
}
//在Launcher进程中运行,其余Constructor/start/stop在Application进程中运行
@Override
public void init() {
try {
String name = Thread.currentThread().getName();
System.out.println("init : " + name);
//书中描述在init方法中禁止创建Stage和Scene实例,实际测试只有调用Stage时才会报错
Scene scene = new Scene(new Group(), 300, 200);
//
//stageInClass.setScene(scene);
Stage stage = new Stage();
stage.setScene(scene);
//stage.show();
//在init或Constructor方法中调用exit方法后,会不调用stop方法
//Platform.exit();
} catch (Exception e) {
System.out.println("error in init method :");
System.out.println(e.getMessage());
}
}
@Override
public void start(Stage primaryStage) throws Exception {
// TODO Auto-generated method stub
String name = Thread.currentThread().getName();
System.out.println("start : " + name);
Scene scene = new Scene(new Group(), 300, 400);
primaryStage.setScene(scene);
primaryStage.setTitle("start method");
primaryStage.show();
//Platform.setImplicitExit(false);
//Platform.exit();
//System.out.println("Platfrom.exit()");
}
@Override
public void stop() {
String name = Thread.currentThread().getName();
System.out.println("stop : " + name);
}
private Stage stageInClass;
/**
* @param args
*/
/*public static void main(String[] args) {
// TODO Auto-generated method stub
String name = Thread.currentThread().getName();
System.out.println("main : " + name);
Application.launch(FXLifeCycleApp.class, args);
}*/
}