This week's book giveaway is in the JavaScript forum.
We're giving away four copies of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js and have Paul Jensen on-line!
See this thread for details.
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

Why JPanel?  RSS feed

 
Ted Schrey
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In most tutorials, they indicate that to add components you need to first add a JPanel to the JFrame. I seem to be able to add, say a button directly to the JFrame. It seems that all or nearly all of the methods (ex: setLayout(LayoutManager layout)) are available directly to the Frame. Why are panels needed?
 
Darryl Burke
Bartender
Posts: 5167
11
Java Netbeans IDE Opera
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ted Schrey wrote:I seem to be able to add, say a button directly to the JFrame. It seems that all or nearly all of the methods (ex: setLayout(LayoutManager layout)) are available directly to the Frame.

Have you read the API for JFrame?
As a convenience, the add, remove, and setLayout methods of this class are overridden, so that they delegate calls to the corresponding methods of the ContentPane.

The contentPane is usually, but not necessarily, a JPanel. For example, if you need a BoxLayout, you might set a javax.swing.Box as the contentPane.

Building your entire GUI in a JPanel (or Box) and then adding it to the frame, or setting it as its contentPane, does afford the flexibility of being able to reuse the same content in a JFrame, JDialog, JWindow or the now largely obsolete JApplet.

Incidentally, there's a hidden gotcha in the forwarding of methods mentioned in the API quoted. Try setting a BoxLayout to a JFrame. Let us know when you succeed
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!