• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to get a new Frame on the center of the screen?

 
Fernando Sanz
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi guys,
I have a small GUI which will open different frames when you select each item.
What I don't like, is that whenever the program opens a new Frame, it appears in the top left corner of the screen. Is it possible to make it appear in the center of the screen?
Thanks
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are using a JDK 1.4 or newer, you can just pass null into the setLocationRelativeTo() method and the frame will be centered automatically.

Otherwise, you'll have to use setLocation() or setBounds() and use Toolkit.getScreenSize() to calculate the location to put the frame.
 
Fernando Sanz
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Nathan, it works perfectly now
 
satya sahu
Ranch Hand
Posts: 97
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try out this code.
setSize(new Dimension(300,300));
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = getSize();
if (frameSize.height > screenSize.height)
{
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width)
{
frameSize.width = screenSize.width;
}
setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
setSize is of your choice
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!