Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Swing / AWT / SWT and the fly likes Question about container class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Question about container class" Watch "Question about container class" New topic
Author

Question about container class

Nick Petas
Ranch Hand

Joined: Jan 31, 2007
Posts: 38
I am reading 'Java - How to Program' from deitel and I have a question.
What is the difference of using setLayout() or add(new JButton("Left")) directly on the JFrame (that is deitel's style) and using these functions after you get a container (container = getContentPane() ) that I have seen surfing the Internet?
Thank you.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19720
    
  20

There is no difference. In Java 1.4 and before calling these methods on a JFrame or JDialog would throw an error. In Java 5.0 this was changed to forward these calls to the content pane. As such, these days frame.add(xxx) and frame.getContentPane().add(...) are the same.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Nick Petas
Ranch Hand

Joined: Jan 31, 2007
Posts: 38
That's what I thought I just wanted to check it with a more experienced person.
In fact in a class of a FlowLayoutFrame in deitel's book he uses container = getContentPane() in the constructor of the JFrame so that he can use it in an actionPerformed() method of a listener using the command layout.layoutContainer(container) to re-arrange some components in the container.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19720
    
  20

That's something different. LayoutManager.layoutComponent takes a Container so you can't use the frame. However, you should never call this method directly. Container.doLayout() is the way to go to force a re-layout. Again, you can't use this with the frame so you'll need its content pane.

Note that if you add or remove controls during runtime invalidate() followed by repaint() is the way to go. (In Swing you should use revalidate() instead of invalidate()).
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Question about container class