简体   繁体   中英

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.

So in JDialog constructor, you should have something like:

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(...); method.

I usually call the following method:

dialog.setLocationRelativeTo(parent);

Link to 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.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(). 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.

If your JDialog has not been rendered yet, JFrame.getSize() might give you a zero size. In that case, you can use JDialog.getPreferredSize() to find out how big it will be once it's rendered on-screen.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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