【问题标题】:Open JFrame from JDialog and it shows on top of JDialog从 JDialog 打开 JFrame,它显示在 JDialog 的顶部
【发布时间】:2014-03-07 11:57:10
【问题描述】:

这是场景, 我的JFrame 有一个按钮,单击它会打开一个JDialog,它是一个模型对话框。 JDialog 有另一个按钮,我想打开另一个 JFrmae 点击它时打开。

结果:打开另一个Jframe,但它不会出现在顶部。它显示在对话框下方。我想在该对话框顶部打开第二个JFrame

可以使用secondFrame.setAlwaysOnTop(true);,但我无法控制关闭或移动它。

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
public class FrameTest
{
    public static void main(String args[])
    {
        JFrame firstFrame = new JFrame("My 1st Frame");
        JButton button = new JButton("Frame Click");

        button.addActionListener(new ActionListener()
        {

            @Override
            public void actionPerformed(ActionEvent e)
            {
                JDialog dialog = new JDialog();
                dialog.setSize(100, 100);
                dialog.setModal(true);
                JButton button1 = new JButton("Dialog Click");

                button1.addActionListener(new ActionListener()
                {
                    @Override
                    public void actionPerformed(ActionEvent e)
                    {
                        JFrame secondFrame = new JFrame("My 2nd Frame");
                        secondFrame.setVisible(true);
                        secondFrame.setSize(400, 200);
                        secondFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        secondFrame.setAlwaysOnTop(true);
                     }
                });

                dialog.add(button1);
                dialog.setVisible(true);
            }
        });

        firstFrame.add(button);
        firstFrame.setVisible(true);
        firstFrame.setSize(400, 200);
        firstFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

【问题讨论】:

  • 查看模态类型。另外,您是否考虑过不使用 jdialog 而只使用框架?您对框架有更多的控制权(在我看来)。
  • The Use of Multiple JFrames, Good/Bad Practice?。请参阅已接受的答案以获得更好的解决方案。
  • 你知道dialog.setModal(true);是什么意思吗?

标签: java swing user-interface jframe jdialog


【解决方案1】:

JDialog 有另一个按钮,我想打开另一个 JFrmae 打开时 点击它。

不要那样做。一个典型的 Swing 应用程序有一个主 JFrame 和几个 JDialogs。看这个话题The Use of Multiple JFrames, Good/Bad Practice?

结果:另一个 Jframe 打开,但它不会到达顶部。它显示 在对话框下。我想在该对话框顶部打开第二个 JFrame。

当然可以,因为对话框是模态的。

可以使用 secondFrame.setAlwaysOnTop(true);但我无法控制 关闭或移动它。

它不会解决任何问题,因为问题与对话框中的模态有关。请参阅这篇文章:How to Use Modality in Dialogs 以了解模态的工作原理。 this answer也有解释。

【讨论】:

    猜你喜欢
    • 2015-08-03
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    • 2020-12-14
    • 1970-01-01
    • 2015-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多