• Post Reply Bookmark Topic Watch Topic
  • New Topic

Positioning Buttons in JPanel

 
Bryan James Ilaga
Greenhorn
Posts: 1
Java Notepad Windows
  • Mark post as helpful
  • send pies
  • 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!
 
Rob Camick
Ranch Hand
Posts: 2699
10
  • Mark post as helpful
  • send pies
  • 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.
 
Campbell Ritchie
Marshal
Posts: 52516
118
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
… and welcome to the Ranch
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!