Java Reference
In-Depth Information
purposes: they can be used as a canvas that one draws on or they can be used as
containers to embed further graphical components.
In Swing the class JPanel implements panels. We list the constructor and some
methods and then present an example program that demonstrates the use of the
methods:
JPanel()
setBackground(Color c)
setPreferredSize(Dimension d)
JPanel() is the constructor. The size of panel is set to default values, 10 by 10
pixel on most systems.
setBackground(Color c) sets the background colour of the panel. The class
Color is from the AWT library. There, some colours are predefined, e.g. red by
Color.red .Bydefault the background colour is grey.
setPreferredSize(Dimension d) sets the size of the panel. The class Dimen-
sion is from the AWT library. The constructor has the syntax Dimension(int
width, int height) . Both width and height are in pixels.
It is important
!
to remember that these values are only recommendations for the size of a
component. Depending on the size of other components, the runtime system
might choose different values! The values actually used are determined by a
LayoutManager at runtime. This flexibility is important for Java to be platform-
independent. We describe layout managers later in this chapter.
We now want to embed some panels into a frame. To make them visible and
distinguishable we colour them differently. As mentioned in the introduction, we
shall derive our own class for every non-trivial concept. It might look like some
kind of overkill here, where only the colour of the panel is set. However, we want
to follow the paradigm of object-orientation right from the beginning.
In the following listing we derive our own class ColorPanel from JPanel . Its
two constructors allow a panel to be constructed, each with a given background
colour, and given width and height.
File: its/SimpleFrameWithPanels/ColorPanel.java
1.
package its.SimpleFrameWithPanels;
2.
3.
import java.awt.*;
import javax.swing.JPanel;
4.
5.
6.
public class ColorPanel extends JPanel
{
7.
// Generate a JPanel with background color col.
8.
public ColorPanel(Color col)
9.
{
10.
Search WWH ::




Custom Search