點擊主視窗按鈕彈出子視窗,子視窗包含輸入欄位與功能按鈕;子視窗關閉前,主視窗不可操作(模態)。
JFrame 為頂層視窗,預設非模態;JDialog 專為對話框設計,支援模態模式。
// 主視窗按鈕事件
JDialog dialog = new JDialog(parentFrame, "標題", true); // true = 模態
dialog.setLayout(new GridLayout(3, 2));
dialog.add(new JLabel("姓名:"));
JTextField tfName = new JTextField();
dialog.add(tfName);
dialog.add(new JLabel("年齡:"));
JTextField tfAge = new JTextField();
dialog.add(tfAge);
JButton btnOk = new JButton("確定");
btnOk.addActionListener(e -> {
// 取值處理
dialog.dispose();
});
JButton btnCancel = new JButton("取消");
btnCancel.addActionListener(e -> dialog.dispose());
dialog.add(btnOk);
dialog.add(btnCancel);
dialog.pack();
dialog.setLocationRelativeTo(parentFrame);
dialog.setVisible(true); // 這裡阻塞,直到 dialog 關閉
true 啟用模態,阻塞父視窗輸入焦點。setLocationRelativeTo(parentFrame) 讓對話框居中顯示於父視窗。pack() 自動依元件優選尺寸。getResult() 方法或使用 PropertyChangeListener。完整範例下載:Swing 模態對話框範例
SwingWorker。JWindow 或 JFrame + setAlwaysOnTop(true)。