• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Devaka Cooray
  • Paul Clapham
Sheriffs:
  • Tim Cooke
  • Knute Snortum
  • Bear Bibeault
Saloon Keepers:
  • Ron McLeod
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Ganesh Patekar
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Tim Holloway

What's with this BoxLayout()?

 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a JFrame named frame
If i use the default layout(BorderLayout) or FlowLayout then the below code,


does not throw errors.
But if i use BoxLayout, then the below code

throws an exception at runtime:

java.awt.AWTError: BoxLayout can't be shared



I re-wrote the code as below and it worked.


So why is that other layout managers work directly with JFrame but
BoxLayout works only with JFrame.getContentPane() ?
 
Bartender
Posts: 5167
11
Netbeans IDE Opera Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
None of the layout managers work 'directly' with JFrame. Have you read the API for the method? It's the second sentence you'll want to focus on.
 
Vidur Koushik
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Then why do we have to explicitly specify contentPane while using BoxLayout ,
and not when using BorderLayout?
 
Saloon Keeper
Posts: 10308
217
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The problem is that BoxLayout needs a reference to the container it's laying out. The container it lays out must be the same as the container that has this BoxLayout as its layout manager.

When you write frame.setLayout(new BoxLayout(frame, ...)); BoxLayout has a reference to frame, but the frame doesn't have the box layout as it's layout manager, because frame just forwards the call to the content pane.

It was probably a mistake that JFrame forwards these calls. I almost always create my own JPanel and set a layout manager on it, and then set that panel as the content pane on a JFrame.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!