Java 2D Application with Design Patterns and XML - PowerPoint PPT Presentation

1 / 21
About This Presentation
Title:

Java 2D Application with Design Patterns and XML

Description:

JFrame is top-level, has contentPane and menuBar. ... handle activate/deactivate events. Drawing Application Classes. MyShape {abstract} DrawingModel ... – PowerPoint PPT presentation

Number of Views:108
Avg rating:3.0/5.0
Slides: 22
Provided by: cyndi8
Category:

less

Transcript and Presenter's Notes

Title: Java 2D Application with Design Patterns and XML


1
Chapter 5
  • Java 2D Application with Design Patterns and XML

2
Application high level view
main class (DeitelDrawing) extends JFrame
Title
menuBar
desktopPane
contentPane (border)
frame (DrawingInternalFrame)
3
Containment Hierarchy DrawingInternalFrame
(JInternalFrame)
Title
toolBar (NORTH) DrawingToolBar
contentPane (BorderLayout)
JScrollPane (CENTER)
ViewPanel (JPanel)
drawingView (extends JPanel)
JFrame is top-level, has contentPane and
menuBar. JInternalFrame is not top-level, so
toolbar etc. just goes into layout
4
Sequence Diagram (instantiate DIF)
DrawingInternalFrame
DrawingModel
new
//InternalFrame observes model
add Observer
DrawingView
new (model)
getInstance
// 1 factory for Shape Controllers
ShapeControllerFactory
Drag and Drop Controller
new
getDefaultDragSource
dragSource
DragSource
create DefaultDragGestureRecognizer (drawingView)
setDropTarget
5
Sequence Diagram (instantiate DIF)
DrawingInternalFrame
JPanel
new
viewPanel
add drawingView
JFileChooser/DrawingFileFiler
new
InternalFrameAdapter
// handle activate/deactivate events
addInternalFrameListener
DrawingToolBar
new
6
Drawing Application Classes
DrawingView (JPanel) ltltobservergtgt
1
x, y, width, color height, etc. getXML
base abstract draw, contains
DrawingModel ltltobservablegtgt
MyShape abstract

ZoomDrawing View
MyLine
MyRectangle
MyOval
MyImage
MyText
font size, name, bold, etc.
MyShapeController Factory
1
filename, getImage
MyShapeController abstract
DrawingFile ReaderWriter
abstract startShape endShape modifyShape
1 (open/ save)
DragAndDropController ltltDragGestureListener,
DragSourceListener, DropTargetListenergtgt
BoundedShape Controller
MyLine Controller
MyText Controller
common parameter
TransferableShape ltltTransferablegtgt
AbstractDrawing Action abstract
(openAction etc.)
1
GradientIcon ltltIcongtgt
DeitelDrawing (JFrame/main)
DrawingInternalFrame ltltobservergtgt
(open/ new)
SplashScreen
1 on DrawingToolBar
7
Factory Method Design Pattern
  • Creates objects
  • Based on criteria known at runtime
  • user input
  • system properties
  • calculation
  • etc.
  • new MyShapeController method
  • takes DrawingModel, class name as string
  • returns controller initialized with drawing model
    and class object of correct shape

8
Java Reflection
  • Class class
  • static method forName returns the Class object
    given a class name as a string
  • can use Class object to getName, getConstructor,
    getDeclaredMethod, getPackage, getResource,
    determine if its array, primitive, etc.
  • reflection enables Java to determine information
    about objects and classes at runtime.

9
MyShapeController
  • Sets the DrawingModel (must add shape to a model
    when drawn)
  • creates mouselisteners uses Adapter class
  • sets drawing attributes
  • protected createNewShape method. Uses newInstance
    method to create new object. (remember forName
    created object from string)

10
Singleton Design Pattern
  • Ensures only one instance of object exists
  • Protected, no argument constructor cant
    instantiate object directly
  • provide final method getInstance()
  • can read system property FACTORY_PROPERTY_KEY to
    determine whether to create subclass. Allows new
    factory to be installed at command line.

11
Model-View-Controller
  • The MVC architecture divides an application into
    three parts
  • data components maintain the raw application data
    (model)
  • presentation components provide the visual
    representation(s) of the data (view)
  • input-processing components handle input from the
    user (controller)

12
MVC - continued
  • There can be more than one view of the data.  For
    example, a document could be viewed in outline
    format, in print preview format, and in editing
    format. 
  • Multiple controllers are also possible, such as
    input from the keyboard and the mouse.   When the
    Model is changed by any Controller, it
    automatically notifies all Views.
  • A variant of MVC is the delegate-model
    architecture.   Java Swing components combine the
    view and controller into a single object called a
    delegate.  In such a system, the Delegate
    modifies the Model, which in turn notifies the
    Delegate. 

13
MVC - Observer design pattern
  • Enables loose coupling.
  • Objects interact by invoking methods declared in
    well-known interfaces, rather than invoking
    methods specific to a particular class.
  • java.util.Observable represents a Model in MVC,
    or the subject in the Observer design pattern.
  • The Observable class provides the method
    addObserver which takes one parameter which
    should be an implementation of the interface
    Observer from java.util.Observer.
  • The Observer corresponds to the View in MVC. 
  • When an Observable object is modified, it
    notifies each registered Observer. 
  • An Observable object must invoke method
    setChanged and then notifyObservers. 
  • The notifyObservers method invokes the update
    method of each registered Observer.

14
Drag-and-Drop Controller
  • Flag for whether in drag mode
  • dragGestureRecognized (when user presses mouse
    and starts to drag)
  • Must be in drag mode
  • Get list of shapes
  • Start at end (last placed) by specifying index
    for iterator
  • Use contains method of MyShape to determine if
    this shape selected
  • create TransferableShape
  • startDrag (cursor, attach shape)
  •  drop
  • get Transferable from event
  • find out "flavors" of transferable
  • determine event (drop) location
  • if JavaFileList, accept only jpeg (calls
    dropImages)
  • if TransferableShape, dropShape (add shape at new
    location)
  • else reject
  • dragDropEnd
  • if successful move
  • get Transferable
  • get TransferData - should be a TransferableShape

15
Drag-and-Drop continued
  • TransferableShape implements Transferable
  • Multipurpose Internet Mail Extension (MIME) types
    text string designed to describe data in email
    attachments, now used in more general purpose way
  • Creates new DataFlavor for shapes
    application/x-deitel-shape, Shape
  • getTransferData returns object containing
    transfer data
  • isDataFlavorSupported checks whether the object
    being dragged is supported by this app.

16
JInternalFrame details
  • Not a top-level container
  • Add components to content pane, just like JFrame
  • Must setVisible
  • Doesnt generate window events. Fires internal
    frame events. App uses for ZoomDialog, to ensure
    only visible when frame is active.
  • Can programmatically iconify or maximize.
  • Should set location. Uses offset
    openFrameCount (a static variable of
    DrawingInternalFrame).

17
XML details
  • DocumentBuilderFactory provides DocumentBuilder
  • Document tree representation of xml document
    (DOM)
  • parse one command, translates xml document into
    DOM tree structure
  • Can use dtd to validate (optional)
  • Transformer writes DOM to file

18
Actions in application
  • setSaved- adds or removes from title,
    enables/disables saveAction
  • update setSaved false
  • setFileName in title
  • setTitle frame zoom
  • close dialog if not saved, dispose, return true
    unless cancel
  • open/SaveDrawing/SaveDrawingAs
  • showZoomDialog create/make visible

19
Miscellaneous Details
  • The SplashScreen is a JWindow borderless
    window. Also shows use of Timer class.
  • The ZoomDialog is a non-modal dialog. It is an
    observer of the model DrawingView. Sets an Affine
    transform that applies to all shapes
    (graphics2D.setTransform), based on x and y scale
    factors.

20
Chapter 5 Exercise
  • Add a new shape option.  I chose to add a
    triangle, but you could choose a different
    shape.  I used a GeneralPath to create the shape
    and the BoundedShapeController as the
    controller.  You'll need to be sure the shape is
    Transferable. 
  • Add an option for Transferable shapes to be
    copied (ACTION_COPY), not just moved.
  • Be sure you can save your new shape.

21
Exercise Hints
  • MyShapeControllerFactory
  • update supportedShapes
  • MyTriangle (or whatever shape you create)
  • getXML
  • calls super for base attributes
  • sets type
  • include extra parameters (e.g., x3, y3)
  • draw
  • creates GeneralPath for shape
  • call draw or fill function of Graphics2D
  • contains
  • create GeneralPath
  • call contains method of GeneralPath
  • DrawingFileReaderWriter
  • may want to change location of shapes.dtd
  • String dtd System.getProperty("user.dir")
    "\\shapes.dtd"
  • update shapes.dtd if add fields to xml file
  • update getShapeFromElement to create new type of
    shape, handle additional fields (if any)
Write a Comment
User Comments (0)
About PowerShow.com