• Post Reply Bookmark Topic Watch Topic
  • New Topic

Center a Frame on the Screen

 
Mike Curwen
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm pretty chagrined at having to post this...
But I can't seem to find it in the API!
setSize(x,x); will size a JFrame
show(); will show a JFrame
But what is the code to make it display centered on the screen?
I know this, but it totally escapes me at the moment!
 
David Shepherd
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is how I did it for a dialog box. It seems like there should be a more efficient way to center your frame by using Toolkit.getDefaultToolkit().... somehow. You can get the screen size from the default toolkit and use it to set the location and size of the frame.

public void jMenuHelpAbout_actionPerformed(ActionEvent e)
{
mainFrame_AboutBox dlg = new mainFrame_AboutBox(this);
Dimension dlgSize = dlg.getPreferredSize();
Dimension frmSize = getSize();
Point loc = getLocation();
dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y);
dlg.setModal(true);
dlg.show();
}
 
Mike Curwen
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That jogged my memory, and I did a search in alll *.java files for ToolKit
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!