aspose file tools*
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
Author

Adding a button to a JFrame

Manfredo Kopfinger
Greenhorn

Joined: May 15, 2006
Posts: 7
Hi!

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
Sheriff

Joined: Oct 13, 2005
Posts: 36508
    
  16
This is what the API says in the Container add method (well one of the add methods.)
add

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.

Parameters:
comp - the component to be added
index - the position at which to insert the component, or -1 to append the component to the end
Returns:
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: http://aspose.com/file-tools
 
subject: Adding a button to a JFrame
 
Similar Threads
Getting Error
JFrames
JLabel visible only when resizing
image blanks out... why?
Displaying multiple images