• Post Reply Bookmark Topic Watch Topic
  • New Topic

Difference between JPanel and Container

 
Marcelo Ortega
Ranch Hand
Posts: 528
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I understand that JPanel is a type of Container (because it actually inherits from Container). But what would be the difference between this:

Container content = myFrame.getContentPane();
content.setLayout(new BorderLayout());

and

JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());

The java API quotes about the getContentPane() method: "Returns the contentPane object for this frame."
But there is no such thing as a contentPane object. I beleive the above variable "content" will now be able to hold components, but why use one instead of the other? Advantages, disadvantages?

Thanks very much,
Regards.
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The difference is two fold. One, the first example declares a Container rather than a JPanel so that "content" can be any implementation of Container and is not limited to a JPanel. Two, the first example is fetching the contentPane for "myFrame" where as the second is instantiating a new JPanel.

I think what you're meaning to get at here is the difference and motivations between something like these two snippets:



and



With the current release of Java there is no difference as far as I'm aware. However, there is no guarantee that this will not change. The contentPane is defined as a Container, not a JPanel and while the default uses a JPanel there is no guarantee it always will. If you want to use a JPanel specifically you need to instantiate it yourself and set the contentPane property using setContenPane(). Assuming that it is a JPanel by default assumes implementation details you ought not make assumptions about. As for the layout, the API specifies that it will have a BorderLayout so that assumption is a little more forgiving but I still think it's a bad idea as there's no guarantee there either.

The net effect is that if you just want to use the Container there and you don't care what kind of Container it is then you can just take the default. If you specifically need to use a JPanel or any other type of Container you should instantiate it yourself and then set the content pane explicitly.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!