Java Reference
In-Depth Information
An instance of this JFrame can then be created and made visible as follows:
BasicFrame bf= new BasicFrame("example");
bf.setLocation(50, 100);
bf.setVisible( true );
Placing components in a JFrame
A component is an object that can be placed in some window, like a JFrame .
Figure 17.2 shows a JFrame with five components, which we describe momen-
tarily. That window is an instance of class ComponentExample of Fig. 17.3,
which extends JFrame . Besides a constructor, this class has a method main ,
which creates an instance of the class and makes it visible.
There must be some means to place components in a window. In the Java
GUI system, this is done using a layout manager . A JFrame uses an instance of
class BorderLayout as its layout manager, and in a JFrame , the components are
placed in its content pane . That is why the second statement of the constructor of
ComponentExample retrieves the content pane and stores it in variable cp .
When using a BorderLayout manager, the content pane has five areas:
north, south, east, west, and center. Each area can contain one GUI component.
Get the class of
Fig. 17.2 from
lesson page 17.1
import javax.swing.*;
import java.awt.*;
/** Place components in a JFrame using default layout manager BorderLayout . Components
in the 5 possible positions are: a JButton , two JLabels , a JTextField , a JTextArea. */
public class ComponentExample extends JFrame {
/** Constructor: a hidden window with title t and five components */
public ComponentExample(String t) {
super (t);
Container cp = getContentPane();
cp.add( new JButton("click me"), BorderLayout.EAST);
cp.add( new JLabel("label 1"), BorderLayout.SOUTH);
cp.add( new JLabel("label 2"), BorderLayout.WEST);
cp.add( new JTextField("type here", 22), BorderLayout.NORTH);
cp.add( new JTextArea("type\nhere", 4, 10), BorderLayout.CENTER);
public static void main(String[] args) {
ComponentExample be = new ComponentExample("Placing components");
be.setVisible( true );
Figure 17.3:
A subclass of JFrame with five components
Search WWH ::

Custom Search