This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

LayoutManagers and containers

 
Marcelo Ortega
Ranch Hand
Posts: 528
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi people,

I'm kind of new when it comes to designing a GUI. I find it REAL hard to actually place components where i'd like them. Is the use of LayoutManagers and various containers common in normal Swing GUI?

For example, would i divide the JFrame up into four containers (JPanels):
____
|_||_|
|_||_| (one JFrame, 4 JPanels)

and then each panel can get a diferrent LayoutManager implementation?

Would this be normal? (I can only use the Java Swing API and no other 3rd party project because it's for my SCJD).

And what i don't understand is why the components fill up all of the cells.


Can someone please help me with this design problem i am having?

Thanks and regards,
Marzo.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is it normal to use LayoutManagers and Containers? Yes, of course. The only alternative is to use a "null" LayoutManager and place components at absolute coordinates. That's a terrible idea because just resizing a window breaks it, not to mention how it will break as the GUI is run on different platforms.

How to divide a window into 4 panels with their own LayoutManager? Easy. Set the LayoutManager of the JFrame's content pane to a GridLayout or GridbagLayout, and add four JPanels to that grid. GridLayout is simpler, but GridBagLayout would let the four panel's size vary.

Then you can independently set the LayoutManager of each of the JPanels; they can all be different.

Why do your components "take up the whole panel?" Well, each LayoutManager has its own strategy for laying out components; some of these strategies do, indeed, involve expanding components to fill available space. You need to read the Javadoc for each LayoutManager you use, carefully. JFrames have a BorderLayout by default; JPanels have a FlowLayout by default.

Have a look at the often-neglected Box class and the BoxLayout, which is a sort of improved FlowLayout.
 
Marcelo Ortega
Ranch Hand
Posts: 528
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Ernest.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic