Java Reference
In-Depth Information
JPanels as graphics panels
Component class JPanel has an inherited procedure paint , which is used to
draw lines, rectangles, ovals, text, and the like using methods of class Graphics .
A JPanel can be added to a JFrame , just like any other component. The class
shown in Fig. 17.5 extends class JPanel , so its instances are components that can
be placed in a JFrame .
In the context in which this class GraphicPanelExample is expected to be
used, it will be used only for painting. Therefore, an instance of GraphicPanel
has to set its own size in the constructor, using method setPreferredSize .
Other than the call to this method, there is little new in this class.
Procedure paint in class GraphicPanelExample simply paints the whole
rectangle that makes up the component with color c . However, you can change
this procedure to draw whatever you wanted.
The subclass of JFrame that is defined in Fig. 17.6 illustrates the use of
JPanel components. The constructor creates three instances of GraphicsPanel-
Example and places them into the content pane of the JFrame . All three instances
A footnote on
lesson page 17-
2 discusses this
topic. Also, ob-
tain a copy of
the classes from
page 17-2.
import java.awt.*;
import javax.swing.*;
public class GraphicsPanelExampleLay extends JFrame {
/** Constructor: a frame with title t and three GraphicsPanelExample s */
public GraphicsPanelExampleLay(String t) {
super (t);
JPanel cPane= new GraphicsPanelExample(50, 50,;
JPanel ePane= new GraphicsPanelExample(80, 50,;
JPanel wPane= new GraphicsPanelExample(30, 50, Color.yellow);
Container cp= getContentPane();
cp.add(cPane, BorderLayout.CENTER);
cp.add(ePane, BorderLayout.EAST);
cp.add(wPane, BorderLayout.WEST);
Figure 17.6:
A class with three JPanel s
Figure 17.7:
An instance of the class in Fig. 17.6
Search WWH ::

Custom Search