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?
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With