收录日期:2020/11/30 16:35:28 时间:2012-06-26 07:59:03 标签:java,swing,positioning,jdialog

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?

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();
}

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.