首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Java 自定義 JDialog 返回值模式:模態對話框 + getter 方法

     編輯:程式設計疑難解答

核心模式:模態對話框 + 實例欄位保存結果

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 / JFileChooser 風格

  • JOptionPane.showConfirmDialog 直接回傳 int (YES/NO/CANCEL) — 適合簡單是/否。
  • JFileChooser.showOpenDialog 回傳 int,檔案用 getSelectedFile() 取得 — **同樣是「模態顯示 + 實例 getter」模式**。

總結

自定義 JDialog 返回值標準做法:**模態建構子 + 實例欄位保存結果 + getter 方法**。呼叫端 setVisible(true) 阻塞,關閉後讀取 getter。靜態工廠方法可進一步簡化為單行呼叫。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved