[英]JFrame, toFront(), ActionListener
我的问题是这个。 我得到了两个可以一起工作并一起移动的窗口。
但是,如果我随后打开浏览器或将出现在屏幕前面的内容,然后尝试通过在任务栏上单击它来在前面显示我的程序,则只有一个窗口出现在前面。 对话框在后面,我不知道如何解决。
我知道有函数ToFront(),但是我仍然不知道如何在这种情况下使用它。
无需创建两个JFrame,而是为您的主窗口创建一个JFrame并将所有其他窗口创建为非模式JDialogs,并以JFrame作为其所有者。 这将导致它们被堆叠为一个组。 每当用户将某个产品带到最前面时,所有产品都被带到最前面。
正如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);
将其与其父框架连接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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.