Java Reference
In-Depth Information
public Component add(Component c, int index).
Adds the Component
to the Container at the position specified by index
public Component add(Component c, Object constraints).
Adds the
Component to the Container using the specified constraints
Components are added to a JFrame differently from the way they are
added to a Frame. When using a Frame, you invoke the add() method
directly on the Frame object, adding the components directly to the Frame.
When using a JFrame, you still invoke the add() method, but not on the
JFrame. Instead, you add the components to the content pane of the
JFrame by invoking the add() method on the JFrame's content pane.
You use the getContentPane() method in the JFrame class to obtain a
reference to the content pane of a JFrame. For example, the following
statements add a JButton to the content pane of a JFrame:
JFrame f = new JFrame();
JButton b = new JButton();
Container contentPane = f.getContentPane();
contentPane.add(b);
Notice that the return value of getContentPane() is Container. The add()
method is invoked on the content pane, adding b by using the layout
manager of the content pane.
Which add() method you use depends on which layout manager you are
using. (Layout managers are discussed in the upcoming section called Layout
Managers .) To demonstrate using the add() method, the following AddDemo
program creates a Frame object and adds a Button.
import java.awt.*;
public class AddDemo
{
public static void main(String [] args)
{
Frame f = new Frame(“A simple window”);
Button cancel = new Button(“Cancel”);
f.add(cancel); //Add the Button to the Frame
f.setSize(100,100);
f.setVisible(true);
}
}
Notice that the cancel Button is added to the Frame f. Whenever f is dis-
played, the cancel button is also displayed. Figure 12.3 shows the output of the
AddDemo program. Notice that the Button consumes the entire interior of the
Frame, no matter what size you make the Frame.
Search WWH ::




Custom Search