Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing: positioning dialog on top of existing window

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?

like image 487
sivabudh Avatar asked Nov 04 '09 23:11

sivabudh


3 Answers

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.

like image 58
sivabudh Avatar answered Nov 15 '22 17:11

sivabudh


I usually call the following method:

dialog.setLocationRelativeTo(parent);

Link to Javadocs

like image 33
Chris B. Avatar answered Nov 15 '22 17:11

Chris B.


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.

like image 29
rob Avatar answered Nov 15 '22 15:11

rob