JavaFX ComboBox 對應 Swing JComboBox。通過 cells 屬性接受 ComboBoxCell 序列構建下拉項;text 屬性定義顯示文本,支持 HTML 富文本(含圖片);selection 綁定模型索引實現雙向同步。

ComboBox {
selection: bind model.selectedImageIndex
cells: bind foreach (imageName in model.imageFiles)
ComboBoxCell {
text: bind "<html><table><tr><td><img src='.../{imageName}'/></td><td>{imageName}</td></tr></table></html>"
}
}
多個 ComboBox、ListBox、RadioButton 共享同一模型屬性 selectedImageIndex,實現跨組件選中狀態自動同步——這正是 JavaFX 聲明式綁定的威力。
Tree 封裝 Swing JTree,提供聲明式構建方式。根節點通過 root 屬性指定 TreeCell,子節點遞歸構建。
Tree {
root: TreeCell {
text: "Tree"
cells: [
TreeCell { text: "colors", cells: [ ... ] },
TreeCell { text: "food", cells: [ ... ] }
]
}
}

模型包含 Person 類(父、母、子女關係)。使用 bind lazy 實現子節點懶加載:僅當用戶展開節點時才遞歸構建子樹,避免一次性構建巨大對象圖。
function descendantTree(p: Person) {
TreeCell {
selected: bind p.selected
text: bind p.name
cells: bind lazy foreach (c in p.children) descendantTree(c)
}
}

通過 RadioButton 切換 showDescendants 標誌,動態替換 root 綁定表達式,實現「後代/祖先」視圖無縫切換。
Table 封裝 JTable。定義 columns(TableColumn 序列)與 cells(每行 TableCell 序列)。支持列寬、對齊、工具提示、條件渲染(如是否素食顯示 Yes/No)。

Table {
columns: [
TableColumn { text: "First Name" },
TableColumn { text: "Sport", width: 100 },
TableColumn { text: "# of Years", alignment: TRAILING },
TableColumn { text: "Vegetarian", alignment: CENTER }
]
cells: bind foreach (p in model.people)
[ TableCell { text: bind p.firstName },
TableCell { text: bind p.sport },
TableCell { text: bind "{p.numYears}" },
TableCell {
text: bind if p.vegetarian then "Yes" else "No"
toolTipText: bind "{p.firstName} {p.lastName} {if not p.vegetarian then 'eats' else 'does not eat'} meat"
}
]
}
Table 內置滾動,無需額外 ScrollPane。
| JavaFX 組件 | 對應 Swing 組件 |
|---|---|
| TextField | JFormattedTextField |
| PasswordField | JPasswordField |
| TextArea | JTextArea |
| EditorPane | JEditorPane |
| TextPane | JTextPane |

示例展示:TextField/PasswordField 綁定模型雙向同步;TextArea 設置字體、自動換行;EditorPane 渲染 HTML;TextPane 支持嵌入圖片與組件(如 Button)。

雙向綁定實現攝氏/華氏聯動:模型定義 trigger on Temp.celsius = value { farenheit = 9/5 * celsius + 32 },Spinner/Slider 的 value 綁定模型屬性,拖動任一控件即更新另一單位。Slider 支持刻度、標籤(如冰點 32°F、沸點 212°F)自定義。