Hello World 計劃
以下程式碼建立一個簡單的使用者介面,其中包含單個 Button,可在單擊時將 String 列印到控制檯。
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class HelloWorld extends Application {
@Override
public void start(Stage primaryStage) {
// create a button with specified text
Button button = new Button("Say 'Hello World'");
// set a handler that is executed when the user activates the button
// e.g. by clicking it or pressing enter while it's focused
button.setOnAction(e -> {
//Open information dialog that says hello
Alert alert = new Alert(AlertType.INFORMATION, "Hello World!?");
alert.showAndWait();
});
// the root of the scene shown in the main window
StackPane root = new StackPane();
// add button as child of the root
root.getChildren().add(button);
// create a scene specifying the root and the size
Scene scene = new Scene(root, 500, 300);
// add scene to the stage
primaryStage.setScene(scene);
// make the stage visible
primaryStage.show();
}
public static void main(String[] args) {
// launch the HelloWorld application.
// Since this method is a member of the HelloWorld class the first
// parameter is not required
Application.launch(HelloWorld.class, args);
}
}
Application 類是每個 JavaFX 應用程式的入口點。只有一個 Application 可以啟動,這是使用
Application.launch(HelloWorld.class, args);
這將建立作為引數傳遞的 Application 類的例項,並啟動 JavaFX 平臺。
以下對程式設計師來說非常重要:
- 首先,
launch建立了Application類的新例項(在本例中為HelloWorld)。因此Application類需要一個無引數建構函式。 - 在建立的
Application例項上呼叫init()。在這種情況下,Application的預設實現不執行任何操作。 start用於Appication例項,主要Stage(= window)被傳遞給方法。在 JavaFX Application 執行緒(Platform 執行緒)上自動呼叫此方法。- 應用程式一直執行,直到平臺確定關閉時間。在這種情況下,當最後一個視窗關閉時,這樣做。
- 在
Application例項上呼叫stop方法。在這種情況下,Application的實現什麼都不做。在 JavaFX Application 執行緒(Platform 執行緒)上自動呼叫此方法。
在 start 方法中構建場景圖。在這種情況下它包含 2 個 Nodes:一個 Button 和一個 StackPane。
Button 表示 UI 中的按鈕,StackPane 是 Button 的容器,用於確定它的位置。
建立了 Scene 來顯示這些 Nodes。最後將 Scene 新增到 Stage,這是顯示整個 UI 的視窗。