JFrame、toFront()、ActionListener

JFrame, toFront(), ActionListener

我的问题是这样的。我得到了这两个 windows,它们可以一起工作并一起移动。

但是,如果我随后打开浏览器或其他会出现在屏幕前面的东西,然后我尝试通过在任务栏上单击它来显示我的程序,那么只有一个 window 出现在前面。对话框在后面,我不知道如何修复它。

我知道有 ToFront() 函数,但我仍然不知道如何在这种情况下使用它。

不要创建两个 JFrame,而是为主 window 创建一个 JFrame,并将所有其他 windows 创建为非模态 JDialog,并以 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); 作为第一个构造函数中的行...

 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);