views:

823

answers:

3

Can someone show simple Java Swing code/web resource that will position the popup dialog center-aligned on top of an existing JFrame window when the JFrame's button clicked?

+1  A: 

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.

rob
+5  A: 

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 this this pointer of JFrame to your dialog, and call setLocationRelativeTo(...); method.

ShaChris23
I didn't realize that method existed; pretty handy!
rob
+2  A: 

I usually call the following method:

dialog.setLocationRelativeTo(parent);

Link to Javadocs

Chris B.