2025/12/01

JavaFX 03 Layout

JavaFX Layout 在 javafx.layout package 裡面,有以下類別 HBox, VBox, Border Pane, Stack Pane, Text Flow, Anchor Pane, Title Pane, Grid Pane, Flow Panel,Pane 類別是所有類別的母類別。

create a layout

建立 layout 有以下步驟

  1. create node

  2. 以 layout 的類別產生 instance

  3. 設定 layout 屬性

  4. 將 nodes 加入 layout

create nodes

ex:

//Creating a text field 
TextField textField = new TextField();       

//Creating the play button 
Button playButton = new Button("Play");       

//Creating the stop button 
Button stopButton = new Button("stop");

產生 layout instance

HBox hbox = new HBox();

設定layout屬性

hbox.setSpacing(10);

將 nodes 加入 layout

//Creating a Group object  
hbox.getChildren().addAll(textField, playButton, stopButton);

Layouts

類別 抽象基底類別 說明
Region 抽象基底類別 支援背景、邊框、padding、最小/最大尺寸等,不直接用於排版。
Layout 類別 排版方式 特性 / 用途
Pane 手動設定每個子節點的位置 最基本容器,無自動排版功能。需搭配 setLayoutX/Y() 使用。
HBox 水平排版 將子節點由左至右排列,可設定間距、對齊與每個節點的伸縮比例。
VBox 垂直排版 將子節點由上至下排列,支援間距、對齊、節點高度調整等。
StackPane 子節點重疊排版 最後加入的節點在最上層,適合建立背景圖層或合成式 UI。
BorderPane 五區域:Top / Bottom / Left / Right / Center 適合標準應用主畫面分區(類似 HTML 的 frameset)。分成 Top/Bottom/Left/Right/Center 五個區域
GridPane 表格樣式的列/欄排列 可自由定義 row/column spans,類似 HTML table。
FlowPane 水平/垂直「流動」排列 當空間不夠時,自動換行/換列(類似 CSS flex-wrap: wrap)。
TilePane 固定格大小的網格排列 每個子節點占用相同大小的 tile 區塊,整齊對齊適合 icon 排列等用途。
AnchorPane 錨定(Anchor)子節點邊距 可將節點固定在上下左右的邊界距離,類似 CSS 的 absolute 定位。
ScrollPane 提供可滾動內容區塊 包含一個子節點,支援垂直與水平捲軸。

另外在 javafx.scene.control.TabPane,雖然名稱是 TabPane,但並不是一種 layout,而是 control 元件,TabPane 可建立一個多頁籤的畫面,每一個頁籤,都能容納一種內容節點,通常是 Pane

Example

以下實例,是利用 TabPan 製作這些 Pane layout 的 sample

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;

public class LayoutExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        TabPane tabPane = new TabPane();

        tabPane.getTabs().add(tab("Pane", createPaneExample()));
        tabPane.getTabs().add(tab("HBox", createHBoxExample()));
        tabPane.getTabs().add(tab("VBox", createVBoxExample()));
        tabPane.getTabs().add(tab("StackPane", createStackPaneExample()));
        tabPane.getTabs().add(tab("BorderPane", createBorderPaneExample()));
        tabPane.getTabs().add(tab("GridPane", createGridPaneExample()));
        tabPane.getTabs().add(tab("FlowPane", createFlowPaneExample()));
        tabPane.getTabs().add(tab("TilePane", createTilePaneExample()));
        tabPane.getTabs().add(tab("AnchorPane", createAnchorPaneExample()));
        tabPane.getTabs().add(tab("ScrollPane", createScrollPaneExample()));

        Scene scene = new Scene(tabPane, 600, 500);
        primaryStage.setTitle("JavaFX Layout Example");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private Tab tab(String title, Pane content) {
        Tab tab = new Tab(title);
        tab.setContent(content);
        return tab;
    }

    private Pane createPaneExample() {
        Pane pane = new Pane();
        Rectangle rect = new Rectangle(50, 50, 100, 100);
        rect.setFill(Color.CORNFLOWERBLUE);
        pane.getChildren().add(rect);
        return pane;
    }

    private Pane createHBoxExample() {
        HBox hbox = new HBox(10, new Button("One"), new Button("Two"), new Button("Three"));
        hbox.setPadding(new Insets(10));
        hbox.setAlignment(Pos.CENTER);
        return hbox;
    }

    private Pane createVBoxExample() {
        VBox vbox = new VBox(10, new Label("Top"), new Button("Middle"), new TextField("Bottom"));
        vbox.setPadding(new Insets(10));
        vbox.setAlignment(Pos.CENTER);
        return vbox;
    }

    private Pane createStackPaneExample() {
        StackPane stackPane = new StackPane();
        Rectangle background = new Rectangle(200, 100, Color.LIGHTGRAY);
        Label label = new Label("On Top");
        stackPane.getChildren().addAll(background, label);
        stackPane.setPadding(new Insets(10));
        return stackPane;
    }

    private Pane createBorderPaneExample() {
        BorderPane borderPane = new BorderPane();
        borderPane.setTop(new Label("Top"));
        borderPane.setBottom(new Label("Bottom"));
        borderPane.setLeft(new Button("Left"));
        borderPane.setRight(new Button("Right"));
        borderPane.setCenter(new TextArea("Center"));
        borderPane.setPadding(new Insets(10));
        return borderPane;
    }

    private Pane createGridPaneExample() {
        GridPane grid = new GridPane();
        grid.setPadding(new Insets(10));
        grid.setHgap(10);
        grid.setVgap(10);
        grid.add(new Label("Name:"), 0, 0);
        grid.add(new TextField(), 1, 0);
        grid.add(new Label("Email:"), 0, 1);
        grid.add(new TextField(), 1, 1);
        return grid;
    }

    private Pane createFlowPaneExample() {
        FlowPane flow = new FlowPane(10, 10);
        flow.setPadding(new Insets(10));
        for (int i = 1; i <= 8; i++) {
            flow.getChildren().add(new Button("Button " + i));
        }
        return flow;
    }

    private Pane createTilePaneExample() {
        TilePane tile = new TilePane(10, 10);
        tile.setPadding(new Insets(10));
        tile.setPrefColumns(4);
        for (int i = 1; i <= 8; i++) {
            tile.getChildren().add(new Label("Tile " + i));
        }
        return tile;
    }

    private Pane createAnchorPaneExample() {
        AnchorPane anchor = new AnchorPane();
        Button button = new Button("Anchored Button");
        anchor.getChildren().add(button);
        AnchorPane.setTopAnchor(button, 20.0);
        AnchorPane.setLeftAnchor(button, 30.0);
        return anchor;
    }

    private Pane createScrollPaneExample() {
        VBox longVBox = new VBox(10);
        for (int i = 1; i <= 50; i++) {
            longVBox.getChildren().add(new Label("Line " + i));
        }
        ScrollPane scrollPane = new ScrollPane(longVBox);
        scrollPane.setFitToWidth(true);
        return new VBox(scrollPane);
    }

    public static void main(String[] args) {
        launch(args);
    }
}

References

JavaFX GridPane Layout

2025/11/24

JavaFX Application

JavaFX 製作的 GUI application,因為以 java 實作,能夠跨平台運作。

application structure

Application (程式入口)
└── Stage (主視窗)
    └── Scene (場景)
        └── Scene Graph (節點樹)
            ├── Layouts (VBox, HBox, BorderPane, etc.)
            │   └── Controls (Button, Label, etc.)
            └── Other nodes (Canvas, WebView, etc.)
Scene (有一個 Root Node)
└── Root Node (Parent)
    ├── Branch Node (Parent)
    │   ├── Leaf Node (Control)
    │   └── Leaf Node (Shape)
    └── Branch Node (Group)
        └── Leaf Node (ImageView)

Stage

包含application內所有 objects,類別是 javafx.stage.Stage,primary stage 由 platform 建立,並以參數傳遞給 Application 的 start()

stage 有兩個參數決定位置:Width, Height,並分為 content area 與 decorations,呼叫show() 可顯示 stage 的 contents

Stage 是最上層的 container (window),只有一個主要的 Stage,javafx 支援五種類型的 stages

  • Primary Stage

    javafx runtime 產生的第一個初始 windows

    Main application window,由 star(Stage) 取得

    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("Primary Stage");
        primaryStage.show();
    }
  • Secondary Stage

    可用來產生dialogs, tools, secondary views

    其他 window/dialog,以 new Stage() 產生

    Stage secondaryStage = new Stage();
    secondaryStage.setTitle("Secondary Stage");
    secondaryStage.show();
  • Model Stage

    特殊的 secondary stage,會阻斷跟其他 window 的互動

    Blocking dialogs,new Stage() + initModality(..) 產生

    Stage modalStage = new Stage();
    modalStage.initModality(Modality.APPLICATION_MODAL);
    modalStage.setTitle("Modal Dialog");
    modalStage.showAndWait();  // blocks until closed
  • Transparent Stage

    沒有 title bar, border, shadow,沒有 decorations 的 stage

    Custom UI, shaped windows,以 initStyle(StageStyle.TRANSPARENT) 產生

    Stage transparentStage = new Stage();
    transparentStage.initStyle(StageStyle.TRANSPARENT);
    transparentStage.setScene(new Scene(root, 300, 200));
    transparentStage.getScene().setFill(Color.TRANSPARENT);
    transparentStage.show();
  • Undecorated/Utility

    Undecorated Stage: no title bar, no close/minimize/maximize buttons

    Utility Stage: styled like a small tool window (depends on OS), useful for small popups or tool palettes.

    Tool windows, splash screens,以 StageStyle.UNDECORATED/UTILITY 產生

    Stage undecoratedStage = new Stage();
    undecoratedStage.initStyle(StageStyle.UNDECORATED);
    undecoratedStage.show();
    
    Stage utilityStage = new Stage();
    utilityStage.initStyle(StageStyle.UTILITY);
    utilityStage.show();

Scene

scene 包含了 scene graph 所有內容,類別是 javafx.scene.Scene,每一個 scene object instance 只能加入一個唯一的 stage

Scene Graph and Nodes

scene graph 是樹狀結構,裡面是 scene 的內容, node 是 scene graph 裡面的 visual/graphical object

  • Container (Parent)

    可包含子節點,用來排版,是 branch node 不是 leaf

    類別 說明
    Group 不處理排版,純粹容器
    Region 所有 layout class 基礎
    Pane 絕對位置排版
    VBox, HBox 垂直 / 水平排版容器
    BorderPane 上下左右中五區域排版
    StackPane 子節點重疊排列
    GridPane 表格式佈局
    AnchorPane 固定邊界排版(類似 CSS)
  • Control (互動元件)

    是 leaf node,可直接跟 user 互動

    類別 說明
    Button 按鈕
    Label 顯示文字
    TextField 單行文字輸入
    TextArea 多行文字輸入
    CheckBox 核取框
    RadioButton 單選按鈕
    ComboBox 下拉選單
    ListView 清單顯示
    TableView 表格資料顯示
    TreeView 樹狀階層顯示
    Slider 拖拉式數值選擇器
    ProgressBar 進度條
    MenuBar 選單列
    TabPane 分頁容器
  • Geometrical (graphical) 2D/3D object (Shape)

    leaf node,用在自訂 UI,或是繪圖功能

    類別 說明
    Rectangle 矩形
    Circle 圓形
    Ellipse 橢圓
    Line 線條
    Polygon 多邊形
    Polyline 折線
    Arc 弧形
    Path 任意路徑
  • Media

    Audio/Video/Image

    類別 說明
    ImageView 顯示圖片
    MediaView 播放音訊或影片視訊
    Canvas 提供 2D 自訂繪圖區域
    WebView 嵌入網頁(HTML/CSS/JS)
    Text 顯示純文字(非 Control)
  • Transform/特效用 node

    類別 說明
    SubScene 場景中的獨立子場景
    SnapshotView 拍攝其他節點的快照
    Group 提供無排版的節點群組
    Clip 裁剪圖形
    Effect (陰影等) 雖不是 Node,但可附加在 Node 上

Node 有三類

  • Root Node

  • Branch/Parent Node

    • Group

    • Region

    • WebView

  • Leaf Node

Example

import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class JavafxSample extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        //Creating a line object
        Line line = new Line();

        //Setting the properties to a line
        line.setStartX(100.0);
        line.setStartY(150.0);
        line.setEndX(500.0);
        line.setEndY(150.0);

        //Creating a Text object
        Text text = new Text();
        //Setting font to the text
        text.setFont(new Font(45));
        //setting the position of the text
        text.setX(50);
        text.setY(150);
        //Setting the text to be added.
        text.setText("Welcome to JavaFx Demo");

        //creating a Group object
        Group group = new Group( );
        //Retrieving the observable list object
        ObservableList list = group.getChildren();
        //Setting the text object as a node to the group object
        list.add(text);
        list.add(line);


        //Creating a Scene by passing the group object, height and width   
        Scene scene = new Scene(group, 600, 300);
        //setting color to the scene 
        scene.setFill(Color.ALICEBLUE);

        //Setting the title to Stage. 
        primaryStage.setTitle("Sample Application");
        //Adding the scene to Stage 
        primaryStage.setScene(scene);
        //Displaying the contents of the stage 
        primaryStage.show();
    }

    public static void main(String args[]) {
        launch(args);
    }
}
java --module-path /java/javafx-sdk-25.0.1/lib/ --add-modules javafx.controls JavafxSample

執行結果

2025/11/17

JavaFX Architecture

JavaFX 是 Java 製作 Content-Rich Client application 的 API。

Architecture

整個 API 的架構如下,包含了 2D 3D Graphic 以及 Web Engine,還有 GUI 的 UI 元件

重要的 API package 如下:

  • javafx.animation

    產生 transition based animations,例如 javafx nodes 的 fill, fade, rotate, scale, translation

  • javafx.application

    控制 JavaFX application 的 life cycle

  • javafx.css

    對 JavaFX GUI application 增加類似 css styling 的功能

  • javafx.event

    傳遞及處理事件

  • javafx.geometry

    產生及控制 2D object

  • javafx.stage

    JavaFX application 的最上層的 container class

  • javafx.scene

    支援 scene graph 的類別,提供 canvas, chart, control, effect, image, input, layout, media, paint, shape, text, transform, web 等等功能

scene graph, node

JavaFX application 是以 Scene Graph 實作,建構 GUI application 的起點就是 scene graph,裡面是 nodes。

node 是一個 visual/graphical object,可能是

  • geometrical (graphical) objects

    2D/3D 物件,例如 circle, rectangle, polygon

  • UI controls

    例如 Button, Checkbox, Text Area

  • Containers

    layut panes,例如 Border Pane, Grid Pane, Flow Pane

  • Media elements

    例如 audio, video, image objects

scene graph 就是由很多 nodes 組合而成的,nodes 會有類似以下的階層式架構

類似這樣的架構,在實際上的 application 可能會是這樣

scene graph 裡面的每一個 node 都有單一一個 parent,唯一一個沒有 parents 的就是 root node。每一個 node 可以有多個 children,沒有 children 的 node 就是 leaf node,如果有 children 的 node 就稱為 branch node。

每一個 node instance 只能被加入到一個 scene graph 一次,node 可能會是 Effects, Opacity, Transforms, Event Handlers, Event Handlers, Application Specific States

Prism

prism 是高效硬體加速的 graphical pipeline,在 JavaFX 用來 render graphics,可 render 2D/3D graphics

為了產生 graphic,prism 會使用

  • DirectX 11 on Windows 7,D3D11
  • DirectX 12 on Windows 10/11,DX12 跟 DX11 相容,D3D11 最常見
  • OpenGL on Mac and Linux, Embedded Systems.

在啟動 JavaFX application 時,加上 -Dprism.verbose=true 參數,可列印 prism 資訊。如果遇到沒有硬體加速的系統,會自動使用軟體 render。

GWT (Glass Windowing Toolkit)

JavaFX 的底層視窗系統抽象層,對平台視窗、輸入事件、螢幕等系統資源提供抽象,供 JavaFX API 使用,負責處理平台相關的:

  • 視窗建立與管理(window creation)

  • 輸入事件(滑鼠、鍵盤、觸控)

  • 螢幕資訊(顯示器解析度、DPI 等)

  • 視窗裝飾(標題列、邊框)

  • 與作業系統的整合

針對不同 OS(Windows / macOS / Linux)有不同的實作

Quantum Toolkit

是 JavaFX 的主執行環境工具包:

  • 它提供了一個 UI 執行緒(JavaFX Application Thread)

  • 負責把 JavaFX API 呼叫分派到底層子系統(例如 Prism, Glass, Media, WebEngine 等),也就是抽象化 Prism, Glass, Media Engine, and Web Engine 底層元件

  • 實作事件分派、場景圖(Scene Graph)渲染與更新調度

會將 Prism 及 GWT 整合在一起

Quantum Toolkit 的主要任務包括:

功能 說明
管理 JavaFX 主執行緒 即 JavaFX Application Thread
事件循環(Event Loop)處理 包括滑鼠、鍵盤、動畫、定時器等事件
計畫場景更新(Pulse) 定時發出 pulse 信號來觸發重繪
安排渲染與場景圖(Scene Graph)同步 確保 UI 狀態與畫面一致

WebView

JavaFX 可嵌入 html content 到 scene graph,透過 WebView 使用 Web Kit 處理這種 content。Web Kit 是 open source web browser engine,可支援 HTML5, CSS, JavaScript, DOM and SVG

WebView 裡面可以使用以下功能

  • 從 local file 或是 remote URL render HTML content
  • 支援 history,可往前或往後瀏覽
  • reload content
  • 為 web component 套用 effects
  • 編輯 html
  • 執行 javascript
  • 處理事件

Media Engine

JavaFX Media engine 是使用 "Streamer" 這個 open source engine 實作,可支援 video/audio content playback

audio 支援 mp3, aac(*.acc *.m4a部分平台預設支援), wav, aiff,不支援 flac, ogg, wma,需要自己處理 GStreamer Plugin

video 支援 mp4 (*.mp4, *.m4v ) 視訊編碼是 h.264,聲音編碼 aac。flv 部分,視訊編碼 h.264 或 Sorenson,聲音編碼為 aac 或 mp3。不支援 WebM (vp8/vp9), mkv, avi, mov

提供三種 component

  • Media Object

  • Media Player

  • Media View

遇到不支援的格式時,會發生 MediaException