Java Reference
In-Depth Information
Chapter 19
Drawing in a Window
WHAT YOU WILL LEARN IN THIS CHAPTER:
• How you can implement Sketcher using the model/view architecture
• How coordinates are defined for drawing on a component
• How you implement drawing on a component
• How to structure the components in a window for drawing
• What kinds of shapes you can draw on a component
• How you implement mouse listener methods to enable interactive drawing operations
In this chapter you look at how you can draw using the Java 2D facilities that are part of the Java Foundation
Classes (JFC). You explore how you draw on a component in an applet and in an application. You investigate
how you can combine the event-handling capability that you learned about in Chapter 18 with the drawing
facilities you explore in this chapter to implement an interactive graphical user interface for creating a sketch.
USING THE MODEL/VIEW ARCHITECTURE
You need to develop an idea of how you're going to manage the data for a sketch in the Sketcher program
before you start drawing a sketch, because this affects where and how you handle events. You already have
a class that defines an application window, SketcherFrame , but this class would not be a very sensible place
to store the underlying data that defines a sketch. For one thing, you'll want to save a sketch in a file, and
serialization is the easiest way to do that. If you're going to use serialization to store a sketch, you don't
want all the fields in the implementation of the SketcherFrame class muddled up with the data relating to the
sketch you have created. For another thing, it makes the program easier to implement if you separate the basic
data defining a sketch from the definition of the GUI. This is along the lines of the Model-View-Controller
(MVC) architecture that I first mentioned in Chapter 17, a variant of which is used in the definition of Swing
components. Ideally, you should manage the sketch data in a class designed specifically for that purpose. This
class is the model for a sketch.
A class that represents a view of the data in the model displays the sketch and handles user interactions, so
this class combines viewing methods with a sketch controller. The general GUI creation and operations that
are not specific to a view are dealt with in the SketcherFrame class. This is not the only way of implementing
the things you want in the Sketcher program, but it's quite a good way.
The model object contains a mixture of text and graphics that make up a sketch. You can call the model
class SketcherModel , and the class that represents a view of the model can have the name SketcherView ,
Search WWH ::




Custom Search