Java Swing: positioning dialog on top of existing window

sivabudh picture sivabudh · Nov 5, 2009 · Viewed 16.5k times · Source

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?

Answer

sivabudh picture sivabudh · Nov 5, 2009

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.