• 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

What's with this BoxLayout()?

 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 15510
363
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic