简体   繁体   English

Java Swing:在现有窗口之上定位对话框

[英]Java Swing: positioning dialog on top of existing window

有人可以显示简单的Java Swing代码/ Web资源,当点击JFrame的按钮时,它会将弹出对话框定位在现有JFrame窗口的顶部吗?

Oh..it's pretty simple: 哦..这很简单:

Say you have a JFrame that contains a JDialog, and you want the JDialog (when opened) to be right on top of JFrame. 假设您有一个包含JDialog的JFrame,并且您希望JDialog(打开时)位于JFrame之上。

So in JDialog constructor, you should have something like: 所以在JDialog构造函数中,你应该有类似的东西:

public class MyDialog extends JDialog 
public MyDialog(JFrame parent) 
{
    super.setLocationRelativeTo(parent); // this will do the job
}

In other words, pass JFrame pointer to your dialog, and call setLocationRelativeTo(...); 换句话说,将JFrame指针传递给对话框,并调用setLocationRelativeTo(...); method. 方法。

I usually call the following method: 我通常称之为以下方法:

dialog.setLocationRelativeTo(parent);

Link to Javadocs 链接到Javadocs

What kind of popup dialog are you talking about? 你在谈论什么样的弹出式对话框? If you're using a JOptionPane or something similar, set its parent component to the JFrame and it will automatically center on top of the JFrame window. 如果您正在使用JOptionPane或类似的东西,请将其父组件设置为JFrame,它将自动居中于JFrame窗口的顶部。

JOptionPane.showMessageDialog(frame, "Hello, World!");

If you are creating your own JDialog, you can get the JFrame's position using JFrame.getLocation() and its size using JFrame.getSize(). 如果要创建自己的JDialog,可以使用JFrame.getLocation()获取JFrame的位置,使用JFrame.getSize()获取其大小。 The math is pretty straightforward from there; 那里的数学很简单; just compute the center of the JFrame and subtract half the width/height of the JDialog to get your dialog's upper left corner. 只计算JFrame的中心并减去JDialog的宽度/高度的一半以获得对话框的左上角。

If your JDialog has not been rendered yet, JFrame.getSize() might give you a zero size. 如果你的JDialog还没有渲染,JFrame.getSize()可能会给你一个零大小。 In that case, you can use JDialog.getPreferredSize() to find out how big it will be once it's rendered on-screen. 在这种情况下,您可以使用JDialog.getPreferredSize()来查看它在屏幕上呈现后的大小。

If you want a modal and centered dialog on a window ... 如果你想在窗口上有一个模态和居中的对话框......

In the dialog's constructor: 在对话框的构造函数中:

class CustomDialog extends JDialog {
    public CustomDialog(Frame owner, String title, boolean modal) {
        super(owner, title, modal);
        setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);

        ...

        setSize(150, 100);
        setLocationRelativeTo(owner);
    }
}

To display the dialog (using a button, etc.): 要显示对话框(使用按钮等):

public void actionPerformed(ActionEvent e) {
    dialog.setVisible(true);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM