Java Reference
In-Depth Information
In previous chapters, we used the
DrawingPanel
class to create simple two-dimensional
graphics. In this final section, we'll analyze
DrawingPanel
to determine how it works
and implement a basic version of the class.
When we created the
DrawingPanel
class, we had two major design goals. The first
was to provide an easy way for client code to access a
Graphics
object. The second
was to provide a simple interface so that the client did not need to know about calling
paintComponent
,
repaint
, and other complex methods.
The graphics drawn by the client onto a
DrawingPanel
are actually drawn onto a
BufferedImage
object stored inside it. The
DrawingPanel
declares a
BufferedImage
as a field and initializes it in its constructor. When the client calls
getGraphics
on the
DrawingPanel
, the program returns a reference to the buffered
image's graphics pen. To place the buffered image onto the screen, we set it as the
icon for a
JLabel
.
The start of the
DrawingPanel
class looks a lot like the code for the GUIs that we
developed in this chapter. It begins by declaring various graphical components as
fields. The fields are the overall window frame, the
Graphics
object for the onscreen
buffered image, and a panel to hold the image:
public class DrawingPanel {
private JFrame frame; // overall window frame
private JPanel panel; // drawing surface
private Graphics g; // drawing pen
...
}
The constructor of the
DrawingPanel
accepts two parameters that represent the
panel's width and height. It initializes the fields and constructs the
BufferedImage
to serve as the persistent buffer where shapes and lines can be drawn. The class
also adds a few methods for the client, such as
getGraphics
,
setBackground
,
and
setVisible
. The following lines of code form an initial version of its com-
plete code:
1 // A simple interface for drawing persistent images.
2 // Initial version without events.
3
4
import
java.awt.*;
5
import
java.awt.image.*;
6
import
javax.swing.*;
7
8
public class
DrawingPanel {
Search WWH ::
Custom Search