• 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

Why JPanel?

 
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
Bartender
Posts: 5167
11
Netbeans IDE Opera Java
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic