Java Reference
In-Depth Information
Merely constructing various component objects does not place them onto the
screen; you must add them to the frame so it will display them. A frame acts as a
container, or a region to which you can add graphical components. To add a compo-
nent to a JFrame , call the frame's add method and pass the appropriate component as
a parameter.
The following program creates a frame and places two buttons inside it:
1 // Creates a frame containing two buttons.
2
3 import java.awt.*;
4 import javax.swing.*;
5
6 public class ComponentsExample {
7 public static void main(String[] args) {
8 JFrame frame = new JFrame();
9 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
10 frame.setSize( new Dimension(300, 100));
11 frame.setTitle("A frame");
12
13 JButton button1 = new JButton();
14 button1.setText("I'm a button.");
15 button1.setBackground(Color.BLUE);
16 frame.add(button1);
17
18 JButton button2 = new JButton();
19 button2.setText("Click me!");
20 button2.setBackground(Color.RED);
21 frame.add(button2);
22
23 frame.setVisible( true );
24 }
25 }
You'll notice a pattern in this code. When you create a component, you must do
the following things:
Construct it.
Set its properties, if necessary.
Place it on the screen (in this case, by adding it to the frame).
 
Search WWH ::




Custom Search