• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Center jFrame

 
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Moving this to the Swing / JFC / AWT forum...
 
Bartender
Posts: 4121
IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Water! People swim in water! Even tiny ads swim in water:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic