How do I set the position of a dialog so it is centered in it's parent frame?
-
01-10-2019 - |
Question
I have a dialog class with a constructor like the following
public SampleDialog(JComponent parent, String title){
super((Frame)SwingUtilities.getAncestorOfClass(Frame.class, parent), title, false);
setLocationRelativeTo(parent);
init();
}
However, this positions the dialog so that it's upper right hand corner is in the center of it's parent. I would like the dialog's center on top of the parent component's center. How do I do this? Am I doing something wrong?
Solution
I figured it out. I had to move setLocationRelativeTo(parent) to the end of the constructor. It needs to be called after pack() is called, which I was calling in my init method.
public SampleDialog(JComponent parent, String title){
super((Frame)SwingUtilities.getAncestorOfClass(Frame.class, parent), title, false);
init();
setLocationRelativeTo(parent);
}
init(){
// initialization code goes here
pack();
}
OTHER TIPS
I did something similar to this, but I used
Dimension dim = Toolkit.getDefaultToolkit()
and then used .getScreenSize, but I am sure you could use it to get the width and height of your parent application with something like this:
myApplication.setLocation((int)dim.getWidth(),(int)dim.getHeight());
I hope this helps.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow