官术网_书友最值得收藏!

Application class

The most common way to use the JavaFX API is to subclass your application from the javafx.application.Application class. There are three overridable methods in there:

  • public void init(): Overriding this method allows you to run code before the window is created. Usually, this method is used for loading resources, handling command-line parameters, and validating environments. If something is wrong at this stage, you can exit the program with a friendly command-line message without wasting resources on the window's creation.

Note this method is not called on JavaFX Application Thread, so you shouldn't construct any objects that are sensitive to it, such as Stage or Scene.

  • public abstract void start(Stage stage): This is the main entry point and the only method that is abstract and has to be overridden. The first window of the application has been already prepared and is passed as a parameter. 
  • public void stop(): This is the last user code called before the application exits. You can free external resources here, update logs, or save the application state. 

The following JavaFX code sample shows the workflow for all these methods:

Note the comment in the first line—it shows the relative location of this code sample in our book's GitHub repository. The same comment will accompany all future code samples, for your convenience.

// chapter1/HelloFX.java
import javafx.application.Application;
import javafx.scene.*;
import javafx.stage.Stage;

public class FXApplication extends Application {

@Override
public void init() {
System.out.println("Before");
}

@Override
public void start(Stage stage) {
Scene scene = new Scene(new Group(), 300, 250);
stage.setTitle("Hello World!");
stage.setScene(scene);
stage.show();
}

public void stop() {
System.out.println("After");
}
}

Note that you don't need the main() method to run JavaFX. For example, this code can be compiled and run from the command line:

> javac FXApplication.java
> java FXApplication

It shows a small empty window:

主站蜘蛛池模板: 吉木萨尔县| 江孜县| 晋宁县| 大庆市| 嫩江县| 教育| 新源县| 万载县| 博湖县| 珠海市| 永新县| 称多县| 泰宁县| 青海省| 长泰县| 乌鲁木齐市| 诸暨市| 大姚县| 新巴尔虎右旗| 辽宁省| 乐昌市| 会东县| 麻栗坡县| 隆化县| 西丰县| 娱乐| 望城县| 南丹县| 永寿县| 阳春市| 郴州市| 佛山市| 乳山市| 资兴市| 莱西市| 宁海县| 睢宁县| 威海市| 五原县| 家居| 东安县|