Ssd4-unit4

  • November 2019
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Ssd4-unit4 as PDF for free.

More details

  • Words: 5,563
  • Pages: 92
Unit 4. Programming Beyond Controls  

4.1 Object Placement and Drawing 4.2 Adding Interactivity and Undo

4.1 Object Placement and Drawing



4.1.1 Co-ordinate systems and object placement 4.1.2 Drawing primitives 4.1.3 Graphics and Animation



Assessments

 

 

Exercise 8 Multiple-Choice Quiz 9

4.1.1 Co-Ordinate Systems And Object Placement

Left….top property  Twips  Hierarchical Co-ordinate system. 

Left….top property 

Controls’ positions on the screen based on their Top and Left properties(VB6).  Left properties:  indicates

the x coordinate of the control in a Cartesian coordinate system.  Top properties:  indicates the y coordinate. 

based on their Location property (VB2005).  Location : a

object property

Left….top property

origin point (x=0, and y=0) at the top left  y values increasing down the screen. 

unit of measure : Twips(VB6) 

Twips Visual Basic employs it as its special units  is 1/20th of a point—a unit of measure used in printing and typography. 



point currently used in computer-based typography,  is 1/72nd of an inch  1,440 twips per inch  567 twips per cm. 

Twips(VB6) 

device independent : TwipsPerInch is always 1,440 no matter what display device is used  the number of pixels per inch or centimeter can vary from device to device  E.g.,  a typical 75 pixels/inch display screen  a typical 300 or 600 pixel per inch printer  In a device independent unit such as twips, it can be sure the placement and size of objects  E.g.  When need to express measurements in pixels, multiply twips by the values Screen.TwipsPerPixelX and Screen.TwipsPerPixelY to obtain horizontal or vertical pixels 

pixels as measurement units

By default, the Visual Basic coordinate system used pixels as measurement units.  Other units, such as points or inches, are also available;  conversion to these units can be easily accomplished using the GraphicsUnit class 

GraphicsUnit 枚举 成员名称 Display

说明 指定显示设备的度量单位。通常,视频显示使用的单 位是像素;打印机使用的单位是 1/100 英寸。

Document

将文档单位( 1/300 英寸)指定为度量单位。

Inch

将英寸指定为度量单位。

Millimeter

将毫米指定为度量单位。

Pixel

将设备像素指定为度量单位。

Point

将打印机点( 1/72 英寸)指定为度量单位。

World

将世界坐标系单位指定为度量单位。

Hierarchical Co-ordinate system 

The Top and Left properties of a control are expressed relative to the container 



E.g., (0,0) set control will be at the top-left corner of the container

container object uses its own coordinate system.  the

positions of objects placed within the container are expressed relative to that (local) origin not the global origin at the top-left of the screen  Also be called as nested coordinate system.

Hierarchical Co-ordinate system is convenient

when the container moves, need no recalculating all their internal coordinate values  whenever reported and used ,x,y positions are expressed in the coordinate system (local) of the object involved. 

How get x,y position ? 

when mouse button was pressed x,y position of the mouse when its button was pressed:  Private Sub name_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)  the MouseEventArgs parameter e to the event handler provide the x,y position of the mouse when its button was pressed  e.X e.Y  The x,y values are expressed relative to the origin (topleft corner) of the object handling this event. 



It is convenient to use the coordinates to find internal parts of the control  use the user input as the basis for drawing. 

How to convert coordinate systems 

It is necessary to convert an object’s coordinate system  from the

local to global  from the global to local 

E.g., if we wished to draw a line from the center of one object to the center of another, we might need to express this drawing in a coordinate system separate from either of the objects.

To convert coordinate systems 

E.g., The center of Button2



Local localX = Button2.Width/2 localY = Button2.Height/2



global globalX = localX + Button2.Left + FrameB.Left + FrameA.Left globalY = localY + Button2.Top + FrameB.Top + FrameA.Top

To convert coordinate systems 

to convert this global coordinate into the coordinate system of one object  newLocalX

= globalX - FrameA.Left Backdrop.Left newLocalY = globalY - FrameA.Top Backdrop.Top

Code of Conversion function 

the local coordinate system  the global coordinate system.  first parameter : the

control object,  second parameter : and the x or y coordinate

Public Function globalX(insideObj As Object, localX As Single)_ As Single Dim result As Single Dim walkObj As Object ' start with the local position result = localX ' starting with the control whose coordinate system ' this value is expressed in Set walkObj = insideObj ' walk up control/container tree until we get to the ' form at the top While Not (TypeOf walkObj Is Form) ' add offset for that coordinate system result = result + walkObj.Left ' move to the next container up Set walkObj = walkObj.Container Wend globalX = result

Public Function globalY(insideObj As Object, _ localY As Single) As Single Dim result As Single Dim walkObj As Object result = localY Set walkObj = insideObj While Not (TypeOf walkObj Is Form) result = result + walkObj.Top Set walkObj = walkObj.Container Wend globalY = result End Function

Conversion function 

the global coordinate system  the local coordinate system.

' Convert a global x coordinate value to the equivalent ' x position in the local coordinate system of the given ' control object. Public Function localX(insideObj As Object, _ globalX As Single) As Single Dim result As Single Dim walkObj As Object result = globalX Set walkObj = insideObj While Not (TypeOf walkObj Is Form) result = result - walkObj.Left Set walkObj = walkObj.Container Wend Return result End Function

' Convert a global y coordinate value to the equivalent ' y position in the local coordinate system of the given ' control object. Public Function localY(insideObj As Object, _ globalY As Single) As Single Dim result As Single Dim walkObj As Object result = globalY Set walkObj = insideObj While Not (TypeOf walkObj Is Form) result = result - walkObj.Top Set walkObj = walkObj.Container Wend Return result End Function

4.1.2 Drawing Primitives (VB6) 

Picture Box Control



Picture Box – Properties Current X Current Y  BackColor, Forecolor, FillColor  FillStyle 

Picture Box-description (VB6)  





Simple graph : using Line and Shape controls complex drawing : it is often easier to write specific code to create the drawing within a PictureBox control. The PictureBox control is created using the toolbox icon shown Note : the difference between the Image control and the PictureBox control

Picture Box-Properties (VB6) 

CurrentX, CurrentY 



determine the current drawing position.

BackColor, ForeColor, FillColor: determine the color of the next drawing output.    



BackColor indicates the background color of a drawing primitive. ForeColor determines the foreground color for drawing. FillColor determines the color of the interior of filled primitives such as filled rectangles and circles. Colors can be specified at design time by interactively picking them from a palette or named list of colors available in the property editor To specify colors at run time, use  one of a set of predefined constants  special hexadecimal color codes

Color Const (VB6) Constant Name

Color Value

vbBlack

&h000000

vbRed

&h0000FF

vbGreen

&h00FF00

vbBlue

&hFF0000

vbYellow

&h00FFFF

vbMagenta

&hFF00FF

vbCyan

&hFFFF00

vbWhite

&hFFFFFF

Picture Box-Properties (VB6) 

FillStyle 

 

determines whether drawing primitives are created with  interior area filled in (1-Solid),  left blank (0-Transparent),  some other filling effect (such as 4-Upward Diagonal which produces diagonal fill lines oriented with their left side higher than their right). If FillStyle is not set to 0-Transparent, then the current FillColor value determines the color of the lines or area used for filling. If FillStyle is not 1-Solid, then some of the background color (set by BackColor) will show through.

Picture Box-Properties (VB6) 

DrawWidth  



determines the width of lines and borders drawn on objects. This value is always expressed in pixels (not twips).

DrawStyle 



determines the line style used for drawing lines and edges.  0-Solid,  1-Dash,  2-Dot,  3-Dash Dot,  4-Dash Dot Dot,  5-Transparent. Note that all nontransparent lines which have DrawWidth > 1 will be drawn solid

Picture Box-Properties (VB6) 

Font  determines

the font used for the next text drawing (print) operation.  It holds a StdFont object having a series of properties including:  Name  Size  Bold  Italic  Underline

Picture Box-Properties (VB6) 

E.g., to create and use a new font object, code as following is used: Dim myFont As New StdFont myFont.Name = "Arial" myFont.Size = 14 myFont.Bold = True Set myPictureBox.Font = myFont



Note : the Font property is normally assigned using the Set command rather than the conventional assignment  Why?

because it is an object reference

PictureBox Methods (VB6) 

drawnObject.Cls clears the PictureBox to its background color  sets CurrentX and CurrentY to 0,0  Notice: no parameters 

PictureBox Methods (VB6) 

drawnObject.PSet [Step] (x, y) [, color] draws a point centered at the given location  sets CurrentX and CurrentY to that location.  The size of the dot is determined by the DrawWidth property.  If the color is not explicitly provided, the current ForeColor is used.  If no Step keyword is given, the x,y point given is set directly. If the Step keyword is present, then the x,y values given specify a relative offset from the current drawing point.  sample 

PictureBox Methods (VB6) 

drawnObject.Line [ [Step] (x1, y1) ] [Step] - (x2, y2) [, color] [, B [F]] 

draws a line or a rectangle.  the starting point of the line—i.e., "(x1, y1)"—is optional. myObject.Line - (100, 200)  Step indicates that the position being indicated is relative.  E.g., myObject.Line Step (10,15) Step - (20,50)  an optional color may be given.  "B" or "B F" may be given. In that case, the method draws a "box" (i.e., rectangle), or filled "box“  sample

PictureBox Methods (VB6) 

drawnObject.Circle [Step] (x, y), radius [, [ color ] , [ start ] , [ end ] , [ aspect ] ] 





draws a circle, ellipse, or a circular or elliptical arc.  Step indicates center point is relative to the current drawing point  color may optionally be provided  The start and end parameters indicate the starting and ending angles of an arc .Angles are expressed in radians.  aspect parameter determines the aspect ratio for ellipses. If the aspect ratio is given as 1.0 (or omitted) a circle is drawn. E.g., myobject.Circle Step (50,10), 200, , , 2.0,  draw a full ellipse centered at a point 50 to the left and 10 below the current drawing point with a radius of 200. sample

PictureBox Methods (VB6) 

drawnObject.PaintPicture picture, x1, y1, width1, height1, x2, y2, width2, height2  

displays an image or part of an image at a given location. Images must be taken from the Picture property  The first picture parameter is the image to be drawn and is required. This is normally the Picture property of some PictureBox or Image control.  x1, y1 parameters give the position where the top-left corner of the image is to appear. If omitted the current drawing position is used.  width1, height1 parameters specify the size of the image as drawn. If different from the size of the image, the image will be scaled (stretched or shrunk) to fit the size given.  x2, y2, width2, and height2 parameters indicate that only a portion of the image is to be drawn.  If these x2, y2, width2, and height2 are omitted, the full image is drawn.

PictureBox Methods (VB6) 

drawnObject.Print string displays a text string  string parameter is any string expression or any expression whose value can be converted into a string. 

highly recommended: set AutoRedraw to True (VB6) 



Whenever something that affects the screen image of a PictureBox or Form occurs (this is sometimes called damage to the object), the Paint event is sent to the control. E.g.,  



when a window is moved forward to become the active window new areas of the window that were previously covered become exposed.

Who do this? 

It is the responsibility of the Paint event handler (no parameters)  redraw the control  restore its proper appearance.

highly recommended: set AutoRedraw to True (VB6) 

If the AutoRedraw property is set to True  



an extra off-screen copy of the control's image is automatically maintained. This image is then drawn automatically in response to Paint events.

Setting AutoRedraw to True   

simplifies drawing because it allows you to simply draw on the control when it is convenient not worry about writing an explicit Paint event handler. Writing Paint event handlers can be a bit complicate because  it is important not to do anything in a Paint event handler that might cause a new Paint event.

4.1.2 Drawing Primitives

Graphics Description  Methods 

 Clear  DrawLine  DrawRectangle

/ FillRectangle  DrawEllipse / FillEllipse DrawPolygon / FillPolygon  DrawImage  DrawString

Graphics Description

Visual Basic provides a sophisticated Graphics tool kit that offers the ability to create custom graphical displays.  Though drawings can occur anywhere in an interface, in most cases you'll want to display custom graphics within a PictureBox control. 

 Doing so

can keep your code clearer,  clearly delimits the location of your drawing when using the design view.

Graphics Description 

The Graphics class offers a variety of methods to draw primitive shapes: lines, arcs, rectangles, ellipses and polygons.  these primitives can be drawn as simple line shapes or as filled solids.  also offers the ability to draw images from existing image files 



all of the methods are overloaded offer the programmer a variety of ways to express the coordinates necessary to draw the shape.  Personal preference and the needs of the specific application that is being developed will determine which specific representation you'll use. 

demonstrate  



DrawingExample application. The application has 6 relevant controls:  a PictureBox to provide a drawing surface,  a ComboBox for selecting the type of shape to be drawn  four NumericUpDown controls to set the shape's height, width and X and Y coordinates  a Button to draw the shape. These controls can be seen in the design view, below:

examine the code 

setVars() 



pbDrawingSurface_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs)  



This method assigns the values provided by the user to the variables used to draw the shape.

The Paint method is for PictureBox. It draws the shape based on the values assigned in setVars()

cmbDraw_Click(ByVal sender As Object, ByVal e As System.EventArgs)    

This is for the Draw button. first calls setVars() to get the user input then calls the Refresh() method of the PictureBox. Refresh() calls the PictureBox's Paint method to causes the shape to be drawn.

Methods

Drawing operations are implemented as methods of the Graphics class.  The majority of the draw methods are overloaded 

 provides

many options for supplying location parameters.  refer to the Visual Basic documentation for specific information on the methods' signatures.

Methods 

Clear 



Clears the drawing surface using the Color provided in the parameter.

DrawLine Draws a line.  The width, color and style of the line are determined by the parameter Pen (an object) 



DrawRectangle / FillRectangle DrawRectangle method draws rectangle;  FillRectangle draws a solid rectangle.  the width, color and style of the line are determined by the parameter Pen or FillBrush 

Methods 

DrawEllipse / FillEllipse  DrawEllipse

method draws an ellipse;  FillEllipse draws a solid ellipse.  the width, color and style of the line are determined by the parameter Pen or FillBrush 

DrawPolygon / FillPolygon  DrawPolygon method draws

a line based on

parameter an array of Point  FillPolygon similarly draws a sold polygon.  the width, color and style of the line are determined by the parameter Pen or FillBrush

Sample code 

the code creates an array of five points and then draws a polygon on the screen using those points.



Private Sub drawPolygonExample(ByVal e As PaintEventArgs) Dim bluePen As New Pen(Color.Blue) Point

Dim polyPoints(4) As polyPoints(0).X = 1 polyPoints(0).Y = 1

Methods

DrawImage  displays an Image or part of an Image at a given location.  DrawString  displays a text string  the String, Font and Location are passed to the method as parameters. 

Sample code 

creates a String, a Font and a Brush and then draws the string at coordinate 25, 30.

Private Sub drawStringExample(ByVal e As PaintEventArgs)

_

Dim exampleString As String = _ "Here is an example String!" Dim blackBrush As New SolidBrush(Color.Black) Dim drawFont As New Font("Arial", 8) e.Graphics.DrawString(exampleString, _ drawFont, blackBrush, 25, 30) End Sub

4.1.3 Graphics and Animation 





creating simple graphics and images is relatively easy using Visual Basic's Graphics class. sometimes static images are not satisfactory; many interfaces can benefit from the use of animated graphics. Creating animated graphics is also fairly simple: images are drawn using coordinates (just as in static images),  but are then redrawn at intervals using new coordinates. 

steps of building a simple stop watch interface

You must know the contents in section 4.1.1 Coordinate Systems and Object Placement  calculating the coordinates is the most difficult part of this application 

Step 1 : build the watch face 

first build the watch face  the

Start/Stop buttons  Reset button 

this piece requires no animation and will be drawn in a PictureBox control:

Step 2 : draw the face 

To accomplish this we use a subroutine drawWatchFace The subroutine calculates the clock's diameter  draws the actual image 



the subroutine will require three parameters The PictureBox control  how far the clock face will be inset from the edge of the PictureBox and  PaintEventArgs. 



Step 3 : drawing the hands of the watch. 

Drawing a watch with stationary hands is very simple 



The watch needs to track the time 

     

use some DrawLine calls and provide the necessary absolute coordinates. these hands need to be drawn over and over again.

As such, it would be useful to have access to some methods that provide the appropriate coordinates for the watch hands. These coordinates should be based upon the current time. To that end, we will next create two methods that will provide the X and Y coordinates for an individual hand. These values will be based upon the hands current value and the intended length of the hand. It's not necessary to have a perfect understanding of the calculations that are used to obtain the coordinates; you should recognize the role of the totalIncrements variable.

Step 4 : drawing the actual hand

The drawHand subroutine is the longest component of the code, but despite the length, it's not particularly complex.  Each hand will be a polygon with four points 

 these

coordinates will be held in a Point array and passed to the FillPolygon routine;  this polygon will then be outlined in black,  using four drawLine calls.

The clockDrawX() and clockDrawY() methods  

The clockDrawX() and clockDrawY() will help to calculate the necessary coordinates in order to properly draw the hand, some additional information is needed  



the thinkness of the hand and the distance that the hand should overhang the center of the clock.

This information will be provided using the following parameters:     



onObj: the PictureBox in which to draw the watch hand minPos: the current postion for this hand handInset: how far the hand will be inset from the edge of the watch face over: the distance that the hand should overhang the center of the clock thick: the thickness of the hand. This parameter allows us to draw both the micro-second and the second hand using the same routine, despite their difference in appearance. clockInset: how far the clock is inset from the edge of onObj.

Step 5 : call together 

We now have the tools to draw the clock; by providing the current time that the watch should show, we can  then call drawWatchFace,  and then make two calls to drawHand (one to express seconds and one to express micro-seconds). 



Together these calls constitute the drawing of the watch: Using these five methods and routines, you can now create a stationary watch face.  Within the Paint event for the PictureBox object, the call drawWatch(pbWatchFace, 432, e) should position the watch hands appropriately for 4 seconds and 32 microseconds 

The last step : track the time and add animation

you'll need to redraw the watch image at some regular interval while call the drawWatch with the new currentTime parameter.  Visual Basic provides a component allow you to do exactly. 

 The

Timer component triggers a Tick event at the frequency that is specified by its Interval property.  This property is specified in milliseconds.

to complete the stopwatch 



First create a Timer component and set the Interval property to 10 milliseconds (which is equal to 1 micro-second). Create a class-level Integer variable that will track the time -- watchTime. should initialize to 0, and  increment by 1 with each Tick of the Timer. 



This variable then be used in the drawWatch call : 



drawWatch(pbWatchFace, watchTime, e).

The Tick() will also need to refresh the PictureBox that contains the stopwatch.

The remaining steps

Handle the Start/Stop and Reset buttons.  These are fairly simple tasks 

 According to

the current state of the stopwatch.  The Start/Stop button should call Timer1.Start() or Timer1.Stop()  Reset button should reassign the value of watchTime back to 0.

Take assessment

Practical Quiz 4  Multiple-Choice Quiz 9 

4.2 Adding Interactivity And Undo

4.2.1 Adding Interactivity to Drawing  4.2.2 Implementing Undo 

4.2.1 Adding Interactivity to Drawing 

Create Custom Interactive objects   

handling events that are sent to PictureBox controls acting on their inputs modifying their output to create feedback

Handling Events 

Such as:        



Click, DblClick, KeyDown, KeyUp, KeyPress, MouseDown, MouseMove, MouseUp

creating custom interactive objects, handlers typically perform four kinds of actions

Process of Handling 

1. Determine how the inputs relate to any separate parts they may have – picking E.g., in ScrollBar

somewhere else.



, Click in one of its arrows, its thumb, or

2. The object uses information about its current state to determine how the input should be interpreted. E.g., radio button do if a Click occurs

selected or not selected.





when it is currently

3. The object acts on the input. This is normally done by changing values in the model or by directly calling application routines 4. Produce a new drawing of itself If anything about the object that the user can, or should, see has

changed, it would do.

picking

Picking can be implemented in several ways  Simplest is to consider each part in turn and test whether the point is inside the screen area covered by the part. 

 by

testing only the extent or bounding box --the smallest rectangle that encloses the part.

picking 



E.g.,  partPicked = (x >= partX and x < partX + partW and y >= partY and y < partY + partH) When overlap, several different parts to be picked by the same x, y position.  parts drawn last are potentially drawn on top of parts drawn first  picking is normally done in the reverse order of drawing ensures that the pick test will first select the object "on top" of the drawing and not one that is "below" and hidden from the user

4.2.2 Implementing Undo

Undo Capability  A Simplified Undo System  A More Capable Undo System  A Complete Undo System  Using Accessor Methods  Implementing Undo in Visual Basic 

Undo Capability 

What is “Undo”: 





A function to allow the user to "go back"—to change their mind about an operation and put the system back into the state it was in before performing the operation.

Providing a pervasive and reliable undo capability can have an important positive impact on the usability of almost any interactive system. Implementing undo is not always easy, because it effects throughout a system.

Undo Capability 

What is the UNDO do? the primary job is to put the system back into a previous state.  must remember what state the system was in  have a mechanism for restoring the system to that condition on demand.  NOTE : a single operation might be carried out in several internal steps,  keep track of what sets of operations correspond to a single user action. 

the state of a computer system 



where to keep the state of a computer system?  by the set of values currently stored in its various memory locations( variables). the job of undo can be thought of as  recording the old values of various variables when they change  putting those values back On demand

Exception 

For safety. Do not provide undo for these types of changes. information stored on external storage devices.  In order to simplify the implementation of undo most systems consider file manipulation operations to be irreversible and do not provide undo for them.  values that are hidden from the program  E.g., values that the operating system or graphical toolkit do not allow direct access to.  E.g., values that indicate which window in the user interface is the currently active window may not be directly represented or available.  Fortunately, such hidden states are fairly rare. 

maintain "shadow" copies of information  

very few cases where “undo” will not work it is often possible to maintain "shadow" copies of this information.  maintains a duplicate copy of the relevant hidden state information  Each time it performs an operation that modifies that hidden state, it also modifies its local copy to reflect the change.  At the same time, it carefully tracks user input and notes the effects of that input on this duplicate state 

the problem of undo just restoring the value of various variables to some previous state

typical implementation of undo 

starts with a recording of  



This recording is maintained in a stack structure 



what variables have been changed what their old values were. the last values saved are the first values restored.

By limiting the size of the undo stack, we can limit the number of undo's a user can perform.  

By providing a stack of unlimited size we can easily provide unlimited undo to the user. Note :  because operation could potentially change many variables, we must typically provide an unlimited internal undo stack anyway.  limited undo only as a space-saving measure, not because it is dramatically easier to implement.

What a typical implementation of undo must do? 

undo subsystem : be communicated with to takes care of the details of managing an undo stack. 





When change, the undo system would push into an internal undo stack  what changed  what its old value was When undo , the undo system would then pop that information from the stack  what changed  what its old value was

Each part of the system must be prepared to  

accept these previously saved values and restore them.

A Simplified Undo System 

Implementation of an undo subsystem is cleaner in a fully object-oriented system.



the implementation of undo Outline  first be implemented in Java  then be translated into Visual Basic.

Beginning with ……

Defining an interfacelike the following:  implementing the interface 

A simple undo subsystem might then be implemented similar to the following:

note 

The reportChange() would be used to report each change made to the system, with: an object responsible for reversing the change  what was changed  the value before it was changed. 

 



The reportChange() would simply push this information onto its internal undo stack. When an actual undo was to be performed, the last saved value would be popped from the stack. The responsible object would then be asked to reverse the change (via its putBackValue() ).

Why use an interface? 

This structure implements a basic undo in a way that is independent of the exact details of what the objects being changed are or  how they are structured. 





Those details are hidden behind the Reversible interface. As long as various portions of the system implement this interface properly and make the required call to reportChange(), their actions can be undone by the undo subsystem.

A More Capable Undo System 

One problem with the simple undo system 



The user normally expects that the undo will be performed at the granularity they see 



it only undoes one value change at a time.

a single action — may internally change many different values.

Note the proper granularity for an undo may not be entirely obvious and  may be one of the user-interface design decisions that need to be carefully considered and tested. 

How to provide the expected granularity for an undo

it is necessary to record explicitly which sequence of internal actions are associated with a single user action.  This can be done by placing "markers" on the undo stack to indicate 

 where

user actions start  where user actions end

support irreversible actions  

The methods reportCantUndo() and canUndo() were added to support easily irreversible actions. reportCantUndo() called by the application whenever it must perform an irreversible action  perhaps after getting an explicit confirmation from the user 



canUndo() allows the user interface to discover whether an undo will currently have any effect  whether there is anything currently available to undo.  This method can be used to enable and disable a typical undo menu item. 

A Complete Undo System

A final important addition to our general undo system is a redo capability.  If a user is not able to "undo an undo" (i.e., redo), then undo itself would become a dangerous operation to perform (since its effects would not be reversible), and, hence, some of its large benefits would be lost. 

support redo     

We need to retain the values replaced when an undo is performed so that they might be restored. This process is much like the recording of values done for the undo. We can then maintain a redo stack much like the undo stack. The redo stack contains change records that can be used to redo changes that have just been undone. Note 

if new actions are performed by the user, redo of previously undone actions is no longer possible, since the redo stack is destroyed.

Using Accessor Methods 

Implementing an undo still requires code to be placed in many different locations in the system. Each place where a variable is modified in the system, a call to record that change for a possible undo is needed.  Doing this can be a tedious and possibly error-prone task. 



Using accessor (set() / get()) for all variable accesses, implementation of undo can be made substantially simpler. the recording calls (calls to reportChange()) can be embedded inside the write accessor ( set() ).  the reporting is localized in one place  not need to be repeated and cannot be forgotten. 

Using Accessor Methods 

Note : the reverser objects need to be able to modify variables directly without using the set()    

This is because the set() would call reportChange(). This must not occur while restoring a value, since it would produce an infinite loop (why ? think it) To accommodate this, we typically expand the accessor methods to include a restore(). For each variable V we would have setV(), getV(), and restoreV()  the restore() would simply set the variable's value and  do no additional reporting and would not update related values

Implementing Undo in Java and Visual Basic

the source code for an implementation of the Undo system.  Implementations are given for both the Java and VB languages. 



Java Implementation 



http://www.icarnegie.com/content/SSD/SSD4/3.0/norma l/pg-prgmng-beynd-cntrls/pg-interactivity-undo/pgimplemntng-undo/Undo-Java.zip

VB Implementation 

http://www.icarnegie.com/content/SSD/SSD4/3.0/norma l/pg-prgmng-beynd-cntrls/pg-interactivity-undo/pgimplemntng-undo/Undo-VB.zip

Take Assessment

Practical Quiz 4  Multiple-Choice Quiz 10  Exercise 8 

Exam 3

Exam 3 Multiple-Choice  Exam 3 Practical 

The final exam 

Take the certification exam  Certification Exam Multiple-Choice  Certification Exam Practical



It will take 4 hours