这应该可以解决您的问题,正如 VGR 已经说过的那样...非模态对话框将跟随它的父级:
public class FocusMain extends JFrame {
private static FocusMain frame;
private static JDialog dialog;
private JCheckBox checkBox;
private JPanel contentPane;
public static void main(String[] args) {
frame = new FocusMain();
frame.setVisible(true);
dialog = new JDialog(frame);
dialog.setSize(100, 100);
}
public FocusMain() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
setContentPane(contentPane);
checkBox = new JCheckBox("show dialog");
checkBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (checkBox.isSelected()) {
dialog.setVisible(true);
} else {
dialog.setVisible(false);
}
}
});
contentPane.add(checkBox);
}
}
使用扩展的 JDialog,您将需要通过构造函数传递父框架,如果您的构造函数如下所示:public ExtendedJDialog(JFrame parentFrame),那么您可以将其与父框架连接起来,super(parentFrame); 作为构造函数中的第一行。 .
public class FocusMain extends JFrame {
private static FocusMain frame;
private static FocusDialog dialog;
private JCheckBox checkBox;
private JPanel contentPane;
public static void main(String[] args) {
frame = new FocusMain();
frame.setVisible(true);
dialog = new FocusDialog(frame);
}
public FocusMain() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
setContentPane(contentPane);
checkBox = new JCheckBox("show dialog");
checkBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (checkBox.isSelected()) {
dialog.setVisible(true);
} else {
dialog.setVisible(false);
}
}
});
contentPane.add(checkBox);
}
}
和扩展的 JDialog
public class FocusDialog extends JDialog {
public FocusDialog(JFrame parentFrame) {
super(parentFrame);
setSize(100, 100);
}
}
如果您需要对话框来阻止父级,请使用super(parentFrame, true);