Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

What's with this BoxLayout()?  RSS feed

 
Vidur Koushik
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() ?
 
Darryl Burke
Bartender
Posts: 5167
11
Java Netbeans IDE Opera
  • 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?
 
Stephan van Hulst
Saloon Keeper
Posts: 7713
141
  • 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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!