Meaningless Drivel is fun!
The moose likes Swing / AWT / SWT and the fly likes Adding a button to a JFrame Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Adding a button to a JFrame" Watch "Adding a button to a JFrame" New topic

Adding a button to a JFrame

Manfredo Kopfinger

Joined: May 15, 2006
Posts: 7

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

Joined: Oct 13, 2005
Posts: 46344
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.
I agree. Here's the link:
subject: Adding a button to a JFrame
It's not a secret anymore!