Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Center jFrame  RSS feed

 
Graham King
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey, can someone please tell me how to center a jFrame on the screen rather than have it run in the top left?
Also if its code, where do i need to put it? Constructor?
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Blackstar_solar
Welcome to the Java Ranch, we hope you�ll enjoy visiting as a regular however, your name is not in keeping with our naming policy here at the ranch. Please change your display name to an appropriate name as shown in the policy.
Thanks again and we hope to see you around the ranch!!
As for your question, to center the frame you need to get the screen dimensions then center your frame in it.
This will get the screen size:
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
You'll need to import the java.awt package to get the Dimension class.
Then just set the location of your object
setLocation(screenSize.width/2 - this.getWidth(),screenSize.height/2 - this.getHeight());
In order to use the getWidth and getHeight methods your class should extend either JFrame or some other component that is inherited from JComponent.
Hope that helps
 
Dirk Schreckmann
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving this to the Swing / JFC / AWT forum...
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you're using a > 1.4 JDK you can also call setLocationRelativeTo( null ) on the JFrame reference and it will be centered.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!