• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about container class

 
Nick Petas
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20493
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Nick Petas
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20493
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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()).
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic