Fin*_*005 11 java user-interface swing modal-dialog jdialog
我有一个模态设置对话框,这是一个JDialog.在这个设置窗口中,我将一些组件(包括按钮)放到另一个模态设置对话框中,该对话框也是JDialog.我把它们变成了JDialogs,因为这是我所知道的唯一一种模态对话框.
问题是这样的:当我创建主设置对话框时,我必须构建JDialog,或者没有父框架或父框架.由于我的主窗口是JFrame,我可以将其传递给主设置对话框构造函数.但是当我想创建第二个模态设置对话框时,它应该将主设置对话框作为父对象,我找不到获取JDialog的(J)框架的方法.我确实希望将该主要设置对话框作为父对象传递,以便第二个设置对话框在显示时以中心为中心.让我们假设第二个设置对话框没有用于传递位置的构造函数,只是JDialog的构造函数.
有没有办法获得JDialog的(J)框架?我的设置中是否存在设计缺陷,我是否应该使用其他设置对话框?(如果是这样,我应该如何设置这些替代设置对话框?)
谢谢你的帮助,Erik
更新:谢谢大家的答案.他们让我明白,显然并不是绝对有必要拥有JDialog的所有者.我认为对话框需要能够禁用所有者,直到对话框关闭,但显然模态独立于所有者.我还注意到即使对于所有者,对话框仍然不以所有者为中心,所以现在我的代码如下:
public class CustomDialog extends JDialog {
public CustomDialog(String title) {
setModal(true);
setResizable(false);
setTitle(title);
buildGUI();
}
public Result showDialog(Window parent) {
setLocationRelativeTo(parent);
setVisible(true);
return getResult();
}
}
Run Code Online (Sandbox Code Playgroud)
这也允许模态对话框中的模态对话框.
感谢你的帮助!
Gui*_*let 13
不确定你究竟有什么问题,但这里有一个关于你如何拥有多个模态对话框的例子:
import java.awt.BorderLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class TestDialog {
protected static void initUI() {
JPanel pane = newPane("Label in frame");
JFrame frame = new JFrame("Title");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(pane);
frame.pack();
frame.setVisible(true);
}
public static JPanel newPane(String labelText) {
JPanel pane = new JPanel(new BorderLayout());
pane.add(newLabel(labelText));
pane.add(newButton("Open dialog"), BorderLayout.SOUTH);
return pane;
}
private static JButton newButton(String label) {
final JButton button = new JButton(label);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Window parentWindow = SwingUtilities.windowForComponent(button);
JDialog dialog = new JDialog(parentWindow);
dialog.setLocationRelativeTo(button);
dialog.setModal(true);
dialog.add(newPane("Label in dialog"));
dialog.pack();
dialog.setVisible(true);
}
});
return button;
}
private static JLabel newLabel(String label) {
JLabel l = new JLabel(label);
l.setFont(l.getFont().deriveFont(24.0f));
return l;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
initUI();
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
1.请阅读Java SE 6中的New Modality API
2.有没有办法获得JDialog的(J)框架?
Window ancestor = SwingUtilities.getWindowAncestor(this);
Run Code Online (Sandbox Code Playgroud)
要么
Window ancestor = (Window) this.getTopLevelAncestor();
Run Code Online (Sandbox Code Playgroud)