46
Computer Programming Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology [email protected] http://www.cse.dlit.edu.tw/~andres

Computer Programming Andres, Wen-Yuan Liao Department of Computer Science and Engineering De Lin Institute of Technology [email protected] andres

Embed Size (px)

Citation preview

Computer Programming

Andres, Wen-Yuan Liao

Department of Computer Science and EngineeringDe Lin Institute of Technology

[email protected]://www.cse.dlit.edu.tw/~andres

2

Chapter 5

Event-Driven Input and Software Design

Strategies

3

Chapter 5 Topics

Declaring and Instantiating a TextBox Declaring and Instantiating a Button Handling Button click events Converting strings into numeric types Using the object-oriented design (OOD) strategy Using CRC cards Using the Functional Decomposition strategy Using Pseudocode

4

Interface

An interface is a connecting link at a shared boundary that allows independent systems to meet and act on or communicate with each other.

Interface

computer programmer

shared boundary (screen)

5

Event-Driven Programming

VB .NET uses event-driven programming. (事件驅動 ) The user’s interaction with a GUI component is an event that can be processed by the program.

To do so, the programmer must write code inside an event-handling method that is pre-defined in Visual Studio .NET

6

Event Handling (p.110)

Window Closing Opened …Mouse Moved Dragged Clicked …Key Pressed Rleased

Protected Overloads Overrides _ Sub Dispose (ByVal disposing _

as Boolean) ………

End Sub

Public Class Form1 Inherits System.Windows.Forms.Form

Private Sub New (. . . . ) . . .

End Class

Firing a event

Events

Event handler

Program to Hold

7

Graphical User Interfaces

GUIs are built from GUI components (also called widgets for window gadgets).

GUI component classes are part of System.Windows.Forms.Form (Abstract Windowing Toolkit package).

GUIs are event-driven. They generate events when the user interacts with the GUI.

An event is an action such as clicking the mouse, clicking a button, that takes place asynchronously (not at a particular time) with respect to the execution of the program.

8

Some GUI components

Form A kind of window in which components can be placed.

Label A component where text can be displayed.

Button A component that generates an event when the user clicks on it with the mouse.

TextBox A component in which the user can type a value. The user must first place the cursor in the field

by clicking inside the field.

9

Some of the VB.NET Objects Hierarchy

Component

Button Label TextBoxBase

TextBox

Object

10

More of the VB.NET Object Hierarchy

Object

System.Windows.Forms

System.Windows.Forms.Form

System.Windows

11

Steps for using a Windows Form

1 Open a new Windows Application

project

2. Add output control to the default

for (such as a label)

3. Assign data to the output control in

an appropriate event

4. Run the application

12

Public Class Form1Inherits System.Windows.Forms.Form. . . Private Sub Form1_Load (. . . . )

Label1.Text = “Total is $” & totalEnd Sub

End Class

Writing Code for a Form

13

class

Private data

and

methods

New

Dispose

14

Syntax for Instance Method Call

.

InstanceMethodCall

ObjectName.MethodName ( parameter , parameter . . . )

EXAMPLES

Mybase.New()

Console.WriteLine (“Good morning.”)

15

2 Steps for processing an event

Add code template for event by double-clicking control which triggers event

Write code in event method

16

Handling a window event

Window controls have pre-defined events for handling most events occurring during a Windows application

Custom events can be created Events are found by double-clicking the

control that generates event

17

Form Methods

Every form has two methods that are part of the class : New and Dispose

The New method calls methods from the Form base class to create a Form instance.

The Dispose method calls another Dispose method to remove all components from the form and to close the form

18

New Method

Public Sub New()

MyBase.New

' This call is required by Windows Form Designer

InitializeComponent()

' Other code can go here

End Sub

19

Dispose Method

Protected Overloads Overrides Sub Dispose_

(ByVal disposing As Boolean)

If disposing Then

If Not (components Is Nothing) Then

components.Dispose( )

End If

MyBase.Dispose (disposing)

End Sub

20

Public Class Form1 Inherits System.Windows.Forms.Form Const MONTH_NAME As String = "August" 'The name of the month Const MONTH_NUMBER As String = "8" 'The number of the month Const DAY As String = "18" 'The day of the month Const YEAR As String = "2001" 'The four-digit year Dim first As String 'Date in Month day, year format Dim second As String 'Date in day Month year format Dim third As String 'Date in mm/dd/yyyy format Dim fourth As String 'Date in dd/mm/yyyy format

#Region "Windows Form Designer generated code"

Case Study : DateFormats Program

21

Public Sub New() MyBase.New()

'This call is required by the Windows Form Designer InitializeComponent( ) 'Create date formats and display on screen first = MONTH_NAME & " " & DAY & ", " & YEAR lblFirst.Text = first second = DAY & " " & MONTH_NAME & " " & YEAR lblSecond.Text = second third = MONTH_NUMBER & "/" & DAY & "/" & YEAR lblThird.Text = third fourth = DAY & "/" & MONTH_NUMBER & "/" & YEAR lblFourth.Text = fourth

End Sub

22

'Form overrides dispose to clean up the component list. Protected Overloads Overrides Sub Dispose(ByVal_

disposing As Boolean) If disposing Then If Not (components Is Nothing) Then

components.Dispose() End If End If MyBase.Dispose(disposing) End Sub End Sub

#End Region

End Class

23

5.2 Using Button and TextBox

Button – A Component of a form that fires an event when the user clicks on it with the mouse

Text box- A component of a form in which the user can type a value. The user must first place the cursor in the text box by clicking inside the box

(see Figure 5.2 on page 169 of your textbook)

24

5.3 Adding a Text Box to a Form

1. Put a textbox on the form

2. Set the appropriate properties for the textbox

25

5.4 Extracting a Value From a Text Box

textContents = inputBox.Text

InputBox.Text = “Replace me “

lblLabel1.Text = “Enter more data: ”

26

5.5 Steps for using a Button

1. Add a button to the form

2. Set appropriate properties for the

button

3. Write code for button’s Click event

27

'Button’s name is Done

Private Sub Done_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) _Handles Done.Click

End Sub

5.6 A Button’s Click Event

28

Handling A Button Click Event

'Button’s name is Done

Private Sub Done_Click(. . . ) 'Code goes here

End Sub

29

CopyString Program

Textbox Name: inputField Textbox Font : 10 point, Bold Textbox Text: “ “

Textbox Name: outputLabel Textbox Font : 10 point, Bold Textbox Text: “ “

Label Name: entryLabel Label Font : 10 point, Bold Label Text: Enter a string:]

Button Name: button1 Button Text: Copy

30

CopyString Program

Public Class Form1Inherits System.Windows.Forms.Form

#Region " Windows Form Designer generated code "

Public Sub New()MyBase.New()

' This call is required by the Windows Form Designer.InitializeComponent()

'Add any initialization after the InitializeComponent() callEnd Sub

31

' Form overrides dispose to clean up the component list.

Public Overloads Sub Dispose()

MyBase.Dispose()

If Not (components Is Nothing) Then

components.Dispose()

End If

End Sub

.........

Private Sub button1_Click(ByVal sender As System.Object, _ByVal e AsSystem.EventArgs) Handles enter.Click

' Copies the text from the box to the label outputLabel().Text = inputField().Text End SubEnd Class

32

5.8 Converting a String to a Numeric Value

Predefined classBuilt-in Object TypeInteger Int32

Long Int64

Single Single

Double Double

Char Char

33

Converting a String to a Numeric Value

Dim someDouble As Double

someDouble = Double.Parse (“37.89”)

Dim intNumber As Integer

intNumber = Int32.Parse (priceField.Text)

34

5.10 Software Design Strategies

FUNCTIONAL OBJECT-ORIENTED DECOMPOSITION DESIGN

The solution is expressed

in terms of objects

(self-contained entities

composed of data and

operations on that data) that

interact by sending messages

to one another.

The problem is divided into

more easily handled

subproblems, the solutions

of which together create a

solution to the overall

problem.

35

5.11 What is an object?

OBJECT

set of methods(public member functions)

.

.

.

Private data

and

methods

internal state(values of private data members)

36

5.12 Object-Oriented Design

A technique for developing a program in which the solution is expressed in terms of objects -- self- contained entities composed of data and operations on that data.

Text

Copy. ..

Clear

Private dataand

methods

New

Dispose. ..

Show

Private dataand

methods

TextBox Form

37

More about OOD

Languages supporting OOD include: VB .NET,

Java, Smalltalk, Eiffel, CLOS, and Object-Pascal.

A class defines the pattern used when instantiating

an object of that type.

A class generally contains private data and public

operations (called methods).

38

5.13 Functional Decomposition

A technique for developing a program in which the problem is divided into more easily handled subproblems, the solutions of which create a solution to the overall problem.

In functional decomposition, we work from the abstract (a list of the major solution steps for which some implementation details remain unspecified) to the concrete (algorithmic steps for which the implementation details are fully specified).

39

Functional Decomposition

FOCUS is on the sequence of actions (algorithms) required to solve the problem.

BEGINS by breaking the solution into a series of major steps. This process continues until each subproblem cannot be divided further or has an obvious solution.

PROGRAMS are collections of modules that solve subproblems. A module structure chart (hierarchical solution tree) is often created.

DATA plays a secondary role in support of actions.

40

FindWeighted Average

PrintWeighted Average

Module Structure Chart

Main

Print Data

Print Heading

Get DataPrepare File for Reading

41

Two Design Strategies

FUNCTION

FUNCTION

FUNCTION

OBJECT

.

.

. OBJECT

.

.

.

OBJECT

.

.

.

FUNCTIONAL OBJECT-ORIENTED DECOMPOSITION DESIGN

42

Case Study : Rainfall Program

Variables:Name Data TypeForm1 FormentryLabel LabeloutputLabel LabelinputText Textboxenter Buttontotal DoublenumberEntries DoubleAmount Doubleaverage Double

43

Rainfall Program

Public Class Form1Inherits System.Windows.Forms.FormDim amount As Double ' Holds input valueDim average As Double ' Holds computer averageDim total As Double ' Keeps running totalDim numberEntries As Double ' Keeps count of entries

#Region " Windows Form Designer generated code "

Public Sub New()MyBase.New()

' This call is required by the Windows Form Designer.InitializeComponent()

'Add any initialization after the InitializeComponent() call

End Sub

44

' Form overrides dispose to clean up the component list.

Protected Overloads Overrides Sub Dispose(ByVal disposing As_

Boolean)

If disposing Then

If Not (components Is Nothing) Then

components.Dispose()

End If

End If

MyBase.Dispose(disposing)

End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e_

AsSystem.EventArgs) Handles MyBase.Load

total = OR

numberEntries = OR

End Sub

45

Private Sub enter_Click(ByVal sender As System.Object, _

ByVal e AsSystem.EventArgs) Handles enter.Click

' Convert string in inputText to a double value

amount = CDbl(inputText.Text)

numberEntries += 1 ' Increment entries

total = total + amount ' Add value to sum

average = total / numberEntries ' Compute average

outputLabel.Text = average ' Display average

inputText.Text = "" ' Clear input text box

End Sub

End Class

46

Exercises

Chapter4 Exam preparation exercises: 1, 4(計算過程 ),5, 9 Programming warm-up exercises: 3

Chapter5 Quick Check: 2, 6, 7, 8, 9 Exam preparation exercises: 4,9 Programming warm-up exercises: 1, 2, 3

Due Date: 10/21 ( 四 ) 請將題目翻譯成中文 請寫在 A4報表紙上,勿使用電腦列印