public class FontDialog extends JDialog {
private boolean confirmed = false;
private Font selectedFont;
private JTextArea previewArea; // 傳入用於預覽
public FontDialog(Frame owner, JTextArea preview) {
super(owner, "字體選擇", true); // true = 模態
this.previewArea = preview;
initUI();
pack();
setLocationRelativeTo(owner);
}
private void initUI() {
// 建立字體列表、大小、樣式控制項...
JButton btnOk = new JButton("確定");
JButton btnCancel = new JButton("取消");
btnOk.addActionListener(e -> {
confirmed = true;
selectedFont = buildFontFromUI();
setVisible(false); // 關閉對話框,模態阻塞結束
});
btnCancel.addActionListener(e -> {
confirmed = false;
setVisible(false);
});
// 佈局...
}
// 供呼叫端取得結果
public boolean isConfirmed() { return confirmed; }
public Font getSelectedFont() { return selectedFont; }
}
FontDialog dialog = new FontDialog(mainFrame, textArea);
dialog.setVisible(true); // 這裡阻塞,直到使用者按確定/取消關閉
if (dialog.isConfirmed()) {
Font font = dialog.getSelectedFont();
textArea.setFont(font);
// 套用字體...
}
| 關鍵 | 說明 |
|---|---|
super(owner, title, true) | 第三個參數 true 設為**模態**,阻塞呼叫執行緒直到 setVisible(false)。 |
實例欄位 confirmed, selectedFont | 對話框關閉後資料仍保留在物件中,呼叫端透過 getter 取得。 |
setVisible(false) 而非 dispose() | 保留物件狀態供後續取值;若確定不再使用可呼叫 dispose() 釋放資源。 |
建構子傳入 JTextArea preview | 即時預覽用,屬於「輸入參數」,非返回值。 |
public static Font showDialog(Frame owner, Font initialFont) {
FontDialog dialog = new FontDialog(owner, initialFont);
dialog.setVisible(true);
return dialog.isConfirmed() ? dialog.getSelectedFont() : null;
}
// 呼叫端一行搞定
Font newFont = FontDialog.showDialog(frame, currentFont);
if (newFont != null) textArea.setFont(newFont);
JOptionPane.showConfirmDialog 直接回傳 int (YES/NO/CANCEL) — 適合簡單是/否。JFileChooser.showOpenDialog 回傳 int,檔案用 getSelectedFile() 取得 — **同樣是「模態顯示 + 實例 getter」模式**。自定義 JDialog 返回值標準做法:**模態建構子 + 實例欄位保存結果 + getter 方法**。呼叫端 setVisible(true) 阻塞,關閉後讀取 getter。靜態工廠方法可進一步簡化為單行呼叫。