Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Adding a button to a JFrame  RSS feed

Manfredo Kopfinger
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

The book Head First Java (Second Edition, covering Java 5.0) says that when I want to add a button to a JFrame, I have to write:

But I found out that it also works when I only write

What are the differences between the two approaches? Is it favorable to write JFrame.getContentPane().add(button); ?
Campbell Ritchie
Posts: 53774
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is what the API says in the Container add method (well one of the add methods.)

public Component add(Component comp,
int index)

Adds the specified component to this container at the given position. This is a convenience method for addImpl(java.awt.Component, java.lang.Object, int).

Note: If a component has been added to a container that has been displayed, validate must be called on that container to display the new component. If multiple components are being added, you can improve efficiency by calling validate only once, after all the components have been added.

comp - the component to be added
index - the position at which to insert the component, or -1 to append the component to the end
the component comp
See Also:
addImpl(java.awt.Component, java.lang.Object, int), remove(int), validate(), JComponent.revalidate()

If you look you will find several versions of the add() method, which all function as "convenience" methods, and actually call other methods.
You can use add() or getContentPane().add(): both will work. But add() on its own might only work in J5 or later.
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!