Java Reference
In-Depth Information
11.
this .setBackground(col);
12. }
13.
14. // Generate a JPanel with background color col,
15. // width width, and height height
16. public ColorPanel(Color col, int width, int height)
17. {
18.
this .setPreferredSize( new Dimension(width,height));
19.
this .setBackground(col);
20. }
21.
22. }
We embed the ColorPanels into a SimplePanelFrame which is derived from Sim-
pleFrame . Thus a SimplePanelFrame inherits the functions of a SimpleFrame ;in
particular an application will be terminated if the frame is closed. We generate five
ColorPanels in white, red, yellow, green and blue. The white one has a width of
50 pixels and a height of 20 pixels. For the others no size is specified, so they will
have the default size. The panels are then embedded into the frame.
Graphical components are embedded into others as follows. Let us call the com-
ponent into which we want to embed the parent component and the component
to be embedded the child component . Those Swing components into which others
can be embedded have a method add . Then, to embed a component childComp
into another component parentComp , the syntax is
parentComp.add(childComp)
The add -method might have more arguments which, for example, specify align-
ments or positions. There is a difference when embedding into a frame. Here we
!
have to specify that we want to embed into the content pane. Besides the content
pane a JFrame has more panes which we do not discuss here. It can be referred to
by using method getContentPane of JFrame . Then the syntax to embed a com-
ponent childComp into a frame parentFrame is:
parentFrame.getContentPane().add(childComp)
Let us now specify how the components are to be arranged in the content pane.
In order to have platform-independence the designers of Java have given some
flexibility to the graphic system. The programmer only specifies the structure of
!
the arrangement of the components, not their absolute positions. For example, one
specifies that 'component A is to the right of component B' instead of requiring that
'component A is at position ( x
y )'. At runtime, the positions of the components
are determined. This is done by the so-called layout manager which is associated
with the parent component. There are different predefined layout managers, some
of which we describe here. The programmer can define individual ones.
A JFrame has by default a BorderLayout , more precisely the content pane
has a layout manager of type BorderLayout .Itallows the user to place one (big)
central component and up to four components at the borders. The positions are
,
Search WWH ::




Custom Search