JDialog 是 Swing 中的對話框組件,用於從主窗口彈出次級窗口。與 JFrame 類似,均需通過 getContentPane() 獲取容器再添加組件。關鍵區別在於 模態:模態對話框會阻塞父窗口交互,直到對話框關閉;非模態則允許同時操作父窗口。
// 常用構造器 JDialog() // 無參,無父窗口,非模態 JDialog(Frame owner) // 指定父窗口,非模態 JDialog(Frame owner, boolean modal) // 指定父窗口與模態性 JDialog(Frame owner, String title, boolean modal) // 完整指定 JDialog(Dialog owner) // 以 Dialog 為父窗口
public class ConfirmDialog extends JDialog {
private boolean confirmed = false;
public ConfirmDialog(JFrame parent, String message) {
super(parent, "確認操作", true); // 模態
setLayout(new BorderLayout());
add(new JLabel(message), BorderLayout.CENTER);
JPanel btnPanel = new JPanel();
JButton okBtn = new JButton("確定");
JButton cancelBtn = new JButton("取消");
okBtn.addActionListener(e -> { confirmed = true; dispose(); });
cancelBtn.addActionListener(e -> { confirmed = false; dispose(); });
btnPanel.add(okBtn); btnPanel.add(cancelBtn);
add(btnPanel, BorderLayout.SOUTH);
pack(); // 自適應大小
setLocationRelativeTo(parent); // 居中顯示
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
public boolean isConfirmed() { return confirmed; }
// 靜態工廠方法簡化調用
public static boolean showConfirm(JFrame parent, String msg) {
ConfirmDialog dlg = new ConfirmDialog(parent, msg);
dlg.setVisible(true); // 阻塞直到關閉
return dlg.isConfirmed();
}
}
public class JDialogDemo {
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("主窗口");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 300);
frame.setLayout(new FlowLayout());
JButton btn = new JButton("彈出模態對話框");
btn.addActionListener(e -> {
JDialog dialog = new JDialog(frame, "標題", true);
dialog.setLayout(new BorderLayout());
dialog.add(new JLabel("這是一個模態對話框"), BorderLayout.CENTER);
JButton closeBtn = new JButton("關閉");
closeBtn.addActionListener(ev -> dialog.dispose());
dialog.add(closeBtn, BorderLayout.SOUTH);
dialog.pack();
dialog.setLocationRelativeTo(frame);
dialog.setVisible(true); // 阻塞點
});
frame.add(btn);
frame.setVisible(true);
});
}
}
| 主題 | 說明 |
|---|---|
| 模態類型 | DEFAULT_MODALITY_TYPE(應用級)、DOCUMENT_MODAL(文檔級)、TOOLKIT_MODAL(工具包級)、MODELESS(非模態) |
| 關閉操作 | DISPOSE_ON_CLOSE(銷毀)、HIDE_ON_CLOSE(隱藏)、DO_NOTHING_ON_CLOSE(自定義) |
| 數據返回 | 通過實例字段或回調接口傳遞結果,避免靜態變量 |
| 居中顯示 | setLocationRelativeTo(parent) 必須在 pack() 之後調用 |
| 線程安全 | 所有 Swing 操作必須在 EDT(事件分發線程)中執行,使用 SwingUtilities.invokeLater |