Transcript Document

1
T U T O R I A L
19
Microwave
Oven Application
Building Your Own
Classes and Objects
 2009 Pearson Education, Inc. All rights reserved.
2
Outline
19.1 Test-Driving the Microwave Oven
Application
19.2 Designing the Microwave Oven
Application
19.3 Adding a New Class to the Project
19.4 Initializing Class Objects: Constructors
19.5 Properties
 2009 Pearson Education, Inc. All rights reserved.
3
Outline
19.6 Completing the Microwave Oven
Application
19.7 Controlling Access to Members
19.8 Using the Debugger: The Locals Window
 2009 Pearson Education, Inc. All rights reserved.
4
Objectives
In this tutorial you will learn:
■ Create your own classes.
■ Create and use objects of your own classes.
■ Control access to object instance variables.
■ Use keyword Private.
■ Create your own properties.
■ Use the Panel control.
■ Use String methods PadLeft and Substring.
 2009 Pearson Education, Inc. All rights reserved.
5
Introduction
■ You have used several .NET classes:
– Each GUI control is defined as a class.
– Classes String and Random have been used to
create objects.
■ When you use an object of a class, your
application is known as a client of that class.
■ Creating your own classes is a key part of
object-oriented programming.
– As with procedures, classes can be reused.
 2009 Pearson Education, Inc. All rights reserved.
6
19.1 Test-Driving the Microwave Oven Application
Application Requirements
An electronics company has asked you to develop an application
that simulates a microwave oven. The oven contains a keypad that
allows the user to specify the microwave cook time. Once a time is
entered, the user clicks the Start Button to begin the cooking
process. The microwave’s glass window changes color (from gray
to yellow), and a timer counts down one second at a time. Once
the time expires, the color of the microwave’s glass window
returns to gray and the microwave displays the text “Done!” The
user can click the Clear Button at any time to stop the microwave
and enter a new time. A beep is sounded whenever a Button is
clicked and when the microwave oven has finished a countdown.
 2009 Pearson Education, Inc. All rights reserved.
7
Test-Driving the Microwave Oven Application
■ Run the completed application (Fig. 19.1).
– The Buttons’ FlatStyle property has been set to Flat.
– The Label’s BorderStyle property has been set to
FixedSingle.
Label
Microwave’s glass window
Numeric
keypad
(Buttons
appear flat)
Figure 19.1 | Microwave Oven application’s Form.
 2009 Pearson Education, Inc. All rights reserved.
Test-Driving the Microwave
Oven Application (Cont.)
8
■ Click the numeric Buttons to enter a time.
■ Note that you can enter no more than four digits—any
extra digits will not appear (Fig. 19.2).
Figure 19.2 | Microwave Oven application accepts only four digits.
 2009 Pearson Education, Inc. All rights reserved.
Test-Driving the Microwave
Oven Application (Cont.)
9
■ Click the Clear Button to clear your input.
■ Enter an invalid input, such as: 7, 2, 3 and 5
(Fig. 19.3).
Figure 19.3 | Microwave Oven application with invalid input.
 2009 Pearson Education, Inc. All rights reserved.
Test-Driving the Microwave
Oven Application (Cont.)
10
■ Click the Start Button, and note that the number of
minutes has been reset to 00 (Fig. 19.4).
Color yellow simulates
microwave light
Figure 19.4 | Microwave Oven application after invalid input has been
entered and the Start Button clicked.
 2009 Pearson Education, Inc. All rights reserved.
Test-Driving the Microwave
Oven Application (Cont.)
11
■ Click Clear, enter a cook time of 5 seconds, then
click Start (Fig. 19.5).
Figure 19.5 | Microwave Oven application with valid time entered and
inside light turned on (it’s now cooking).
 2009 Pearson Education, Inc. All rights reserved.
Test-Driving the Microwave
Oven Application (Cont.)
12
■ After the microwave finishes counting down to zero,
you should hear a beep and see a change in the GUI
(Fig. 19.6).
Label displays Done! when
cooking is finished
Color returns to default
color to simulate that
cooking has finished
Figure 19.6 | Microwave Oven application after the cooking time has elapsed.
 2009 Pearson Education, Inc. All rights reserved.
13
19.2 Designing the Microwave Oven Application
■ The following pseudocode describes the basic
operation of class Time:
When the time object is created:
Assign input to variables for number of minutes and number of
seconds
When setting the number of minutes:
If the number of minutes is less than 60
Set the number of minutes to specified value
Else
Set the number of minutes to 0
When setting the number of seconds:
If the number of seconds is less than 60
Set the number of seconds to specified value
Else
Set the number of seconds to 0
 2009 Pearson Education, Inc. All rights reserved.
19.2 Designing the Microwave
Oven Application (Cont.)
14
■ The following pseudocode describes the basic
operation of your Microwave Oven class:
When the user clicks a numeric Button:
Sound beep
Display the formatted time
When the user clicks the Start Button:
Store the minutes and seconds
Display the formatted time
Begin countdown—Start timer
Turn the microwave light on
 2009 Pearson Education, Inc. All rights reserved.
19.2 Designing the Microwave
Oven Application (Cont.)
15
When the timer ticks (once per second):
Decrease time by one second
Display new time
If new time is zero
Stop the countdown
Sound beep
Display text “Done!”
Turn the microwave light off
When the user clicks the Clear Button:
Display the text “Microwave Oven”
Clear input and time data
Stop the countdown
Turn the microwave light off
 2009 Pearson Education, Inc. All rights reserved.
Action/Control/Event (ACE) Table for
the Microwave Oven Application
16
■ Use an ACE table to convert the pseudocode into
Visual Basic (Fig. 19.7).
Action
Control/Object
Event
oneButton, twoButton,
threeButton, fourButton,
fiveButton, sixButton,
sevenButton, eightButton,
nineButton, zeroButton
Click
Sound beep
Display the formatted time
displayLabel
startButton
Store the minutes and seconds
timeObject
Display the formatted time
displayLabel
Begin countdown—Start timer
clockTimer
Turn microwave light on
windowPanel
Click
Figure 19.7 | ACE table for the Microwave Oven application. (Part 1 of 2.)
 2009 Pearson Education, Inc. All rights reserved.
Action/Control/Event (ACE) Table for
the Microwave Oven Application (Cont.)
Action
Control/Object
Event
clockTimer
Tick
Decrease time by one second
timeObject
Display new time
displayLabel
If new time is zero
timeObject
Stop the countdown
17
clockTimer
Sound beep
Display text “Done!”
displayLabel
Turn the microwave light off
windowPanel
clearButton
Display the text “Microwave Oven”
displayLabel
Clear input and time data
timeIs,
timeObject
Stop the countdown
clockTimer
Turn microwave light off
windowPanel
Click
Figure 19.7 | ACE table for the Microwave Oven application. (Part 2 of 2.)
 2009 Pearson Education, Inc. All rights reserved.
Adding a Panel Control to the
Microwave Oven Application
18
■ Add a Panel control to the Form by double clicking
the Panel control (
) in the Containers tab of
the Toolbox.
– The main difference between Panels and GroupBoxes is
that GroupBoxes can display a caption.
■ Name the control windowPanel.
– Set its Size to 328, 224 and its Location to 14, 16. Set
the BorderStyle property to FixedSingle.
 2009 Pearson Education, Inc. All rights reserved.
Adding a Panel Control to the
Microwave Oven Application (Cont.)
19
■ Use instance variable timeIs (Fig. 19.8) to store user
input.
Figure 19.8 | Variable timeIs contains the user’s input.
 2009 Pearson Education, Inc. All rights reserved.
20
GUI Design Tip
Use Panels to organize groups of related controls
where the purpose of the controls is obvious. If the
purpose of the controls is not obvious, use a
GroupBox rather than a Panel, because GroupBoxes
can contain captions.
 2009 Pearson Education, Inc. All rights reserved.
21
GUI Design Tip
Although it is possible to have a Panel without a
border (by setting the BorderStyle property to None),
use borders on your Panels to improve user interface
readability and organization.
 2009 Pearson Education, Inc. All rights reserved.
22
GUI Design Tip
A Panel can display scrollbars when it is not large
enough to display all of its controls. To increase
usability, we suggest avoiding the use of scrollbars on
Panels. If a Panel is not large enough to display all of
its contents, increase the size of the Panel or place the
content in multiple Panels.
 2009 Pearson Education, Inc. All rights reserved.
Adding a Panel Control to the
Microwave Oven Application (Cont.)
23
■ One of the numeric Buttons’ Click event handlers is
shown in Figure 19.9.
– Function Beep causes your computer to make a beeping
sound.
– The current Button’s number is appended to timeIs.
When a number is entered,
play a beep, append the
number to the timeIs and
display the new time
Figure 19.9 | Typical numeric event handler.
 2009 Pearson Education, Inc. All rights reserved.
Adding a Panel Control to the
Microwave Oven Application (Cont.)
24
■ The template application has several empty event
handlers (Fig. 19.10).
startButton_Click
creates an object to store
the time and begin cooking
clearButton_Click resets
variables and Label
DisplayTime formats time
information for display
clockTimer_Tick
performs countdown
and updates display
Figure 19.10 | Microwave Oven application’s remaining event handlers.
 2009 Pearson Education, Inc. All rights reserved.
25
Adding a Class to the Microwave Oven Application
■ Select Project > Add Class.
– Enter the class name (Time) in the Name: field and click
Add (Fig. 19.11).
Select Class as new item
Name of new class
Figure 19.11 | Add New Item dialog allows you to create a new class.
 2009 Pearson Education, Inc. All rights reserved.
Adding a Class to the Microwave
Oven Application (Cont.)
26
■ The class appears in the Solution Explorer
(Fig. 19.12).
New file displayed in
Solution Explorer
Figure 19.12 | Solution Explorer displaying the new class file.
 2009 Pearson Education, Inc. All rights reserved.
Adding a Class to the Microwave
Oven Application (Cont.)
27
■ Open Time.vb. (Fig. 19.13).
– Keyword Class indicates that what follows is a class
definition.
– The keywords End Class indicate the end of the class
definition.
– Any methods or variables defined in the body of a class
are considered to be members of that class.
Empty class definition
added by the IDE
Figure 19.13 | Empty class definition.
 2009 Pearson Education, Inc. All rights reserved.
Adding a Class to the Microwave
Oven Application (Cont.)
28
■ The Time class (Fig. 19.14) stores a time value:
– The value for minutes is stored in minuteValue
– the value for seconds is stored in secondValue
Instance variables
store minute and second
information
Figure 19.14 | Time’s instance variables.
 2009 Pearson Education, Inc. All rights reserved.
29
Good Programming Practice
Add comments at the beginning of your classes to
increase readability. The comments should indicate the
name of the file that contains the class and the
purpose of the class being defined.
 2009 Pearson Education, Inc. All rights reserved.
30
Defining a Constructor
■ Add the constructor method New (Fig. 19.15).
■ Whenever an object of that class is instantiated
(created), this constructor method is called.
New is the constructor method
Figure 19.15 | Empty constructor.
 2009 Pearson Education, Inc. All rights reserved.
31
Common Programming Error
Attempting to declare a constructor as a Function
procedure instead of as a Sub procedure and
attempting to Return a value from a constructor are
both syntax errors.
 2009 Pearson Education, Inc. All rights reserved.
32
Defining a Constructor
■ Lines 13–14 (Fig. 19.16) initialize Time’s instance
variables to the values of the constructor’s parameter
variables.
■ A Time object can now be created with the statement
timeObject = New Time(5, 3)
Initialize instance variables
Figure 19.16 | Constructor initializing instance variables.
 2009 Pearson Education, Inc. All rights reserved.
33
Error-Prevention Tip
Providing a constructor to ensure that every object is
initialized with meaningful values can help eliminate
logic errors.
 2009 Pearson Education, Inc. All rights reserved.
34
Defining a Constructor (Cont.)
■ Add lines 6–7 of Fig. 19.17 to MicrowaveOven.vb.
– The class name, Time, is used as a type.
Declare timeObject of
programmer-defined type
Time
Figure 19.17 | Declaring an object of type Time.
 2009 Pearson Education, Inc. All rights reserved.
35
Defining a Constructor (Cont.)
■ Visual Basic is known as an extensible language.
– The language can be “extended” with new data types.
■ Your Time class can be displayed in the IntelliSense
window (Fig. 19.18).
Time appears as a type
in the IDE
Figure 19.18 | Time appearing as a type in an IntelliSense window.
 2009 Pearson Education, Inc. All rights reserved.
36
19.5 Properties
■ Clients of a class usually want to manipulate that
class’s instance variables.
– A class (Person) that stores information about a person.
– Clients who create an object of class Person might want
to modify age.
■ Classes provide properties to allow clients to access
and modify instance variables safely.
– The code in the property typically checks the value to be
assigned and rejects invalid data.
– Minute and Second are two properties used in the Time
class.
 2009 Pearson Education, Inc. All rights reserved.
37
19.5 Properties (Cont.)
■ A property definition may consist of two accessors:
– The Set accessor allows clients to set a property.
timeObject.Minute = 35
– The Get accessor allows clients to get a property.
minuteValue = timeObject.Minute
■ Each property typically performs validity checking—to
ensure that the data assigned to the property is valid.
– Keeping an object’s data valid is also known as keeping
that data in a consistent state.
 2009 Pearson Education, Inc. All rights reserved.
38
Defining Properties
■ Add lines 17–18 of Figure 19.19 to Time.vb below
the constructor, then press Enter.
■ Note the syntax used in a property definition:
– The first line of the property concludes with the keyword
As followed by a data type.
Get accessor retrieves data
Set accessor stores data
Figure 19.19 | Empty Minute property.
 2009 Pearson Education, Inc. All rights reserved.
39
Good Programming Practice
Name each property with a capital first letter.
 2009 Pearson Education, Inc. All rights reserved.
40
Defining Properties (Cont.)
■ When property Minute is referenced, the Get
accessor (Fig. 19.20) should return the value of
minuteValue.
Returning data from a property
Figure 19.20 | Get accessor definition.
 2009 Pearson Education, Inc. All rights reserved.
41
Defining Properties (Cont.)
■ When property Minute is assigned a value
(Fig. 19.21), you want to test whether the value to be
assigned is valid.
Validate minute data
Figure 19.21 | Set accessor definition.
 2009 Pearson Education, Inc. All rights reserved.
42
Defining Properties (Cont.)
■ Add the Second property (Fig. 19.22).
Empty property
Figure 19.22 | Second property.
 2009 Pearson Education, Inc. All rights reserved.
43
Defining Properties (Cont.)
■ Second (Fig. 19.23) is similar to Minute, except that
variable secondValue is being modified and read.
Second property performs
similar data manipulations to
Minute property
Figure 19.23 | Second property definition.
 2009 Pearson Education, Inc. All rights reserved.
44
Defining Properties (Cont.)
■ Use the Minute and Second properties to safely
initialize instance variables in the class’s constructor.
■ When a client calls New and passes values for mm and
ss, the constructor calls the Set accessors to validate
the values (Fig. 19.24).
Safer to assign data to
properties rather than
instance variables,
because Set accessors
perform validity checking
Figure 19.24 | Constructor using properties to initialize variables.
 2009 Pearson Education, Inc. All rights reserved.
45
Completing the Microwave Oven Application
■ second and minute (Fig. 19.25) store the values
entered by the user.
■ PadLeft appends characters to the beginning of a
String.
– A given character is added to the beginning of the String
until it has the proper length.
Ensure timeIs has four
characters for
conversion purposes
Figure 19.25 | Declaring variables for second and minute values.
 2009 Pearson Education, Inc. All rights reserved.
46
Completing the Microwave Oven Application (Cont.)
■ Convert.ToInt32 converts the last two characters of timeIs
to an Integer (Fig. 19.26).
■ Arguments passed to Substring indicate the start and end
of a subset of characters.
– Substring with a single argument returns the characters
after the given index.
– The argument 2 starts with the third character, because
the first character’s index is 0.
Convert input to seconds
and minutes
Figure 19.26 | Form minute and second values from input.
 2009 Pearson Education, Inc. All rights reserved.
47
Completing the Microwave Oven Application (Cont.)
■ When the Time object is instantiated, operator New
allocates the memory in which the Time object will be
stored.
■ The Time constructor is called with the values of minute
and second (Fig. 19.27).
■ The New operator returns a reference to the newly created
object; this reference is assigned to timeObject.
Use keyword New to
create a new object
Figure 19.27 | Creating a Time object.
 2009 Pearson Education, Inc. All rights reserved.
48
Completing the Microwave Oven Application (Cont.)
■ If the time entered was 3 minutes and 20 seconds, the
String that will display for the user is "03:20".
– The format control string "{0:D2}:{1:D2}" indicates
that arguments take the format D2—thus, 8 would be
converted to 08 (Fig. 19.28).
Display cooking time
Figure 19.28 | Displaying time information with separating colon.
 2009 Pearson Education, Inc. All rights reserved.
49
Completing the Microwave Oven Application (Cont.)
■ Note that Time’s properties appear in the IntelliSense
window (Fig. 19.29) when you try to access the
object’s members.
Time’s properties
appear in IntelliSense
Figure 19.29 | Properties of a programmer-defined type also appear in IntelliSense.
 2009 Pearson Education, Inc. All rights reserved.
50
Completing the Microwave Oven Application (Cont.)
■ The Timer is started by setting its Enabled property
to True (Fig. 19.30).
■ The Panel’s BackColor property is set to yellow to
simulate the light inside the microwave oven.
– The Color structure contains several predefined colors.
Start timer and turn light on to
indicate microwave oven is
cooking
Figure 19.30 | Starting the microwave oven countdown.
 2009 Pearson Education, Inc. All rights reserved.
51
Completing the Microwave Oven Application (Cont.)
■ The Panel’s background is set to the Panel’s original
color with the DefaultBackColor property
(Fig. 19.31).
– When a Panel is added, its background takes on the
default background color of the Form.
Resetting Microwave
Oven application
Figure 19.31 | Clearing the Microwave Oven input.
 2009 Pearson Education, Inc. All rights reserved.
52
Completing the Microwave Oven Application (Cont.)
■ Method DisplayTime (Fig. 19.32) is called each time
the user enters another digit.
■ String property Length returns the number of
characters in a String.
– Any characters appended past the first four are removed.
Figure 19.32 | Modifying invalid user input.
 2009 Pearson Education, Inc. All rights reserved.
53
Completing the Microwave Oven Application
■ Line 152 (Fig. 19.33) appends zeros to the front of
timeIs if fewer than four digits were entered.
■ Lines 155–156 use method Substring to isolate the
number of seconds and minutes currently entered.
Figure 19.33 | Display current input.
 2009 Pearson Education, Inc. All rights reserved.
54
Completing the Microwave Oven Application (Cont.)
■ Event handler clockTimer_Tick executes every
second for as long as the Timer is enabled
(Fig. 19.34).
Modify time appropriately
during countdown
Figure 19.34 | Modifying the display during countdown.
 2009 Pearson Education, Inc. All rights reserved.
55
19.7 Controlling Access to Members
■ Keywords Public and Private are called
access modifiers.
– Class members that are declared Public are available
to any client of the class.
– Private makes members available only to methods
and properties of the same class.
 2009 Pearson Education, Inc. All rights reserved.
56
Common Programming Error
Attempting to access a Private class member from
outside its class is a compilation error.
 2009 Pearson Education, Inc. All rights reserved.
57
Software Design Tip
Declare all instance variables of a class as Private.
When necessary, provide Public properties to set and
get the values of Private instance variables.
 2009 Pearson Education, Inc. All rights reserved.
58
Controlling Access to Members
■ In Time.vb, replace keyword Dim in lines 7–8 with
keyword Private (Fig. 19.35).
■ These instance variables are now accessible only
to members of class Time.
Figure 19.35 | Time’s instance variables are Private.
 2009 Pearson Education, Inc. All rights reserved.
59
Controlling Access to Members (Cont.)
■ In MicrowaveOven.vb, replace keyword Dim in lines
4 and 7 with keyword Private (Fig. 19.36).
Figure 19.36 | Microwave Oven’s instance variables are Private.
 2009 Pearson Education, Inc. All rights reserved.
60
Good Programming Practice
Group all Private class members in a class definition,
followed by all Public class members to enhance
clarity and readability.
 2009 Pearson Education, Inc. All rights reserved.
61
Software Design Tip
It is possible to declare the Get and Set accessors
with different access modifiers. One of the accessors
must have the same access as the property, and the
other must be more restrictive than the property. For
example, in a Public property, the Get accessor could
be Public and the Set accessor could be Private to
create a property that is "read-only" to the class’s
clients.
 2009 Pearson Education, Inc. All rights reserved.
62
Controlling Access to Members (Cont.)
■ Add keyword Private to the beginning of method
DisplayTime (Fig. 19.37).
■ Event handlers have the keyword Private
automatically added to their headers because event
handlers are specific to the Form’s class.
Figure 19.37 | Microwave Oven’s methods are Private.
 2009 Pearson Education, Inc. All rights reserved.
63
Good Programming Practice
For clarity, every instance variable or property
definition should be preceded by a member-access
modifier.
 2009 Pearson Education, Inc. All rights reserved.
64
Outline
■ Figures 19.38 and 19.39 present the source
code for the Microwave Oven application.
1
2
3
4
5
6
7
8
9
10
Public Class MicrowaveOvenForm
' contains time entered as a String
Private timeIs As String = ""
' contains time entered
Private timeObject As Time
' event handler appends 1 to time string
Private Sub oneButton_Click(ByVal sender As System.Object, _
11
12
ByVal e As System.EventArgs) Handles oneButton.Click
13
Beep() ' sound beep
14
15
16
(1 of 11 )
Make a "beep" sound by
calling method Beep
timeIs &= "1" ' append digit to time input
DisplayTime() ' display time input properly
End Sub ' oneButton_Click
17
 2009 Pearson Education,
Inc. All rights reserved.
65
Outline
(2 of 11 )
18
' event handler appends 2 to time string
19
Private Sub twoButton_Click(ByVal sender As System.Object, _
20
21
ByVal e As System.EventArgs) Handles twoButton.Click
22
Beep() ' sound beep
23
24
25
timeIs &= "2" ' append digit to time input
DisplayTime() ' display time input properly
End Sub ' twoButton_Click
26
27
' event handler appends 3 to time string
28
Private Sub threeButton_Click(ByVal sender As System.Object, _
29
30
31
32
33
34
ByVal e As System.EventArgs) Handles threeButton.Click
Beep() ' sound beep
timeIs &= "3" ' append digit to time input
DisplayTime() ' display time input properly
End Sub ' threeButton_Click
35
 2009 Pearson Education,
Inc. All rights reserved.
66
Outline
(3 of 11 )
36
37
38
39
' event handler appends 4 to time string
Private Sub fourButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles fourButton.Click
Beep() ' sound beep
timeIs &= "4" ' append digit to time input
DisplayTime() ' display time input properly
End Sub ' fourButton_Click
40
41
42
43
44
45
46
47
' event handler appends 5 to time string
Private Sub fiveButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles fiveButton.Click
48
49
50
51
52
Beep() ' sound beep
timeIs &= "5" ' append digit to time input
DisplayTime() ' display time input properly
End Sub ' fiveButton_Click
53
 2009 Pearson Education,
Inc. All rights reserved.
67
Outline
(4 of 11 )
54
' event handler appends 6 to time string
55
Private Sub sixButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles sixButton.Click
56
57
Beep() ' sound beep
timeIs &= "6" ' append digit to time input
DisplayTime() ' display time input properly
End Sub ' sixButton_Click
58
59
60
61
62
63
' event handler appends 7 to time string
64
65
Private Sub sevenButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles sevenButton.Click
66
67
68
69
70
Beep() ' sound beep
timeIs &= "7" ' append digit to time input
DisplayTime() ' display time input properly
End Sub ' sevenButton_Click
 2009 Pearson Education,
Inc. All rights reserved.
68
Outline
(5 of 11 )
71
72
' event handler appends 8 to time string
73
74
75
76
77
78
79
Private Sub eightButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles eightButton.Click
Beep() ' sound beep
timeIs &= "8" ' append digit to time input
DisplayTime() ' display time input properly
End Sub ' eightButton_Click
80
81
82
' event handler appends 9 to time string
Private Sub nineButton_Click(ByVal sender As System.Object, _
83
84
ByVal e As System.EventArgs) Handles nineButton.Click
85
Beep() ' sound beep
86
timeIs &= "9" ' append digit to time input
87
88
DisplayTime() ' display time input properly
End Sub ' nineButton_Click
 2009 Pearson Education,
Inc. All rights reserved.
69
Outline
(6 of 11 )
89
90
91
92
' event handler appends 0 to time string
Private Sub zeroButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles zeroButton.Click
93
94
95
96
97
Beep() ' sound beep
timeIs &= "0" ' append digit to time input
DisplayTime() ' display time input properly
End Sub ' zeroButton_Click
98
99
100
' event handler starts the microwave oven's cooking process
Private Sub startButton_Click(ByVal sender As System.Object, _
101
102
ByVal e As System.EventArgs) Handles startButton.Click
 2009 Pearson Education,
Inc. All rights reserved.
70
Outline
(7 of 11 )
103
104
Dim second As Integer
Dim minute As Integer
105
106
107
' ensure that timeIs has 4 characters
timeIs = timeIs.PadLeft(4, "0"c)
108
109
110
111
' extract seconds and minutes
second = Convert.ToInt32(timeIs.Substring(2))
minute = Convert.ToInt32(timeIs.Substring(0, 2))
112
113
114
115
116
117
118
119
120
121
122
' create Time object to contain time entered by user
timeObject = New Time(minute, second)
Creating a new object of a
programmer-defined type
displayLabel.Text = String.Format("{0:D2}:{1:D2}", _
timeObject.Minute, timeObject.Second)
Accessing variables of a
programmer-defined type
timeIs = "" ' clear timeIs for future input
clockTimer.Enabled = True ' start timer
 2009 Pearson Education,
Inc. All rights reserved.
71
Outline
(8 of 11 )
123
windowPanel.BackColor = Color.Yellow ' turn "light" on
124
125
126
End Sub ' startButton_Click
127
128
' event handler to clear input
Private Sub clearButton_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles clearButton.Click
129
130
131
132
133
' reset each property or variable to its initial setting
displayLabel.Text = "Microwave Oven"
timeIs = ""
134
135
136
timeObject = Nothing
clockTimer.Enabled = False
windowPanel.BackColor = Control.DefaultBackColor
137
Use property BackColor to
change the Panel’s color
End Sub ' clearButton_Click
138
139
' method to display formatted time in timer window
 2009 Pearson Education,
Inc. All rights reserved.
72
Outline
(9 of 11 )
140
Private Sub DisplayTime()
141
142
143
144
Dim second As Integer
Dim minute As Integer
145
146
147
Dim display As String ' String displays current input
148
149
150
If timeIs.Length > 4 Then
timeIs = timeIs.Substring(0, 4)
End If
Method Substring returns a
subset of characters in a String
151
152
display = timeIs.PadLeft(4, "0"c)
153
154
Method PadLeft called to ensure
that String timeIs contains four
characters
' extract seconds and minutes
' if too much input entered
155
156
157
second = Convert.ToInt32(display.Substring(2))
minute = Convert.ToInt32(display.Substring(0, 2))
158
' display number of minutes, ":" and number of seconds
 2009 Pearson Education,
Inc. All rights reserved.
73
Outline
(10 of 11 )
159
displayLabel.Text = String.Format("{0:D2}:{1:D2}", _
160
161
minute, second)
End Sub ' DisplayTime
162
163
164
' event handler displays new time each second
Private Sub clockTimer_Tick(ByVal sender As System.Object, _
165
166
ByVal e As System.EventArgs) Handles clockTimer.Tick
167
' perform countdown, subtract one second
168
169
If timeObject.Second > 0 Then
timeObject.Second -= 1
170
171
displayLabel.Text = String.Format("{0:D2}:{1:D2}", _
timeObject.Minute, timeObject.Second)
 2009 Pearson Education,
Inc. All rights reserved.
74
Outline
(11 of 11 )
172
173
174
175
176
177
ElseIf timeObject.Minute > 0 Then
timeObject.Minute -= 1
timeObject.Second = 59
displayLabel.Text = String.Format("{0:D2}:{1:D2}", _
timeObject.Minute, timeObject.Second)
Else ' no more seconds
178
179
clockTimer.Enabled = False ' stop timer
Beep()
180
displayLabel.Text = "Done!" ' inform user time is finished
181
182
183
windowPanel.BackColor = Control.DefaultBackColor
End If
End Sub ' clockTimer_Tick
184 End Class ' MicrowaveOvenForm
 2009 Pearson Education,
Inc. All rights reserved.
1
2
' Time.vb
' Represents time data and contains properties.
3
4
Public Class Time
5
6
75
Outline
Keyword Class used to
define a class
' declare Integers for minute and second
7
8
9
Private minuteValue As Integer
Private secondValue As Integer
10
11
12
13
' Time constructor, minute and second supplied
Public Sub New(ByVal mm As Integer, ByVal ss As Integer)
14
15
16
17
Second = ss ' invokes Second Set accessor
End Sub ' New
' property Minute
18
19
20
Public Property Minute() As Integer
' return Minute value
Get
21
22
23
Minute = mm ' invokes Minute Set accessor
Time.Vb
(1 of 2 )
New is the constructor
Assign data to properties,
rather than directly to
instance variables
End Sub keywords end the
constructor definition
Return minuteValue
End Get ' end of Get accessor
 2009 Pearson Education,
Inc. All rights reserved.
24
' set Minute value
25
26
Set(ByVal value As Integer)
' if minute value entered is valid
76
Outline
27
28
If (value < 60) Then
minuteValue = value
29
30
31
Else
minuteValue = 0 ' set invalid input to 0
End If
32
33
End Set ' end of Set accessor
End Property ' Minute
34
35
' property Second
36
Public Property Second() As Integer
37
38
' return Second value
Get
39
Return secondValue
40
End Get ' end of Get accessor
41
42
43
44
' set Second value
Set(ByVal value As Integer)
' if second value entered is valid
(2 of 2 )
Keyword Property used
to define a property
Get accessor returns data
45
46
47
If (value < 60) Then
secondValue = value
Else
48
49
secondValue = 0 ' set invalid input to 0
End If
50
Time.Vb
Set accessor modifies and
validates data
End Set ' end of Set accessor
51
End Property ' Second
52 End Class ' Time
End Property keywords
end property definition
End Class keywords
end class definition
 2009 Pearson Education,
Inc. All rights reserved.
Using the Debugger:
Using the Locals Window
77
■ Set breakpoints in lines 168 and 181 of
MicrowaveOven.vb by clicking in the margin
indicator bar (Fig. 19.40).
Figure 19.40 | Microwave Oven application with breakpoints added.
 2009 Pearson Education, Inc. All rights reserved.
Using the Debugger:
Using the Locals Window (Cont.)
78
■ Start the debugger.
■ Open the Locals window (Fig. 19.41) by selecting
Debug > Windows > Locals.
– The Locals window allows you to view the state of the
variables in the current scope.
Figure 19.41 | Empty Locals window.
 2009 Pearson Education, Inc. All rights reserved.
Using the Debugger:
Using the Locals Window (Cont.)
79
■ Set the microwave oven’s time to 1:01, and click the
Start Button.
■ The Locals window lists all the variables that are in
the scope of clockTimer’s Tick event handler.
– To view the contents of timeObject, click the plus box next
to the word Me.
– Click the plus box next to timeObject (Fig. 19.42).
Property of timeObject
Instance variable of timeObject
Figure 19.42 | Locals window displaying the state of timeObject.
 2009 Pearson Education, Inc. All rights reserved.
Using the Debugger:
Using the Locals Window (Cont.)
80
■ Click the debug toolbar’s Continue Button.
■ Note that the value for the amount of seconds appears
in red (Fig. 19.43) to indicate it has changed.
■ Click the Continue Button again.
Changed values
Figure 19.43 | Locals window displaying changed variables.
 2009 Pearson Education, Inc. All rights reserved.
Using the Debugger:
Using the Locals Window (Cont.)
81
■ In the Locals window, double click the value for
property Second and set it to 0 (Fig. 19.44).
– Now set the value of the Second property to 100.
– The Second property will validates the data and
sets the value to 0.
Value changed by user
Figure 19.44 | Changing the value of a variable in the Locals window.
 2009 Pearson Education, Inc. All rights reserved.