• 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

Positioning Buttons in JPanel

 
Greenhorn
Posts: 1
Notepad Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi! I am new to Java. I want to add buttons to my program. I added buttons on my JPanel named startWindow and added startWindow to a JFrame. The buttons did not position properly. Here is the code:


How should I fix these? Thanks in advance!
 
Rancher
Posts: 3324
32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Don't use setSize(). Don't use setLocation(). Every component in Swing is responsible for determining its own preferred size so the component looks consistent throughout the application and on different platforms.

Swing was designed to be used with "layout managers". The layout manager will determine the size/location of each button. So it overrides the values you used.

The default layout manager for a JPanel is a FlowLayout which means the components are aligned beside one another with a specified gap so the layout looks professional no matter what font/text is used for each component.

Read the section from the Swing tutorial on Using Layout Managers for more information and working examples of layout managers.

Also, the text on buttons is typically not capitalized. Learn by example from other applications that use buttons! For example look at any button used on this website.
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
… and welcome to the Ranch
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic