5.1 Relational and Logical Operators 192 Relational
Download
Report
Transcript 5.1 Relational and Logical Operators 192 Relational
A Introduction to Programming
Using Visual Basic 2010
(Eighth Edition)
David I. Schneider
Instructor
Name:Liang Jiankun
E-Mail:[email protected]
Phone: 23986531
Office: Computer Center
Chapter 7 – Additional
Controls and Objects
7.1 List Boxes and Combo Boxes
7.2 Eight Additional Controls and Objects
7.3 Multiple-Form Objects
7.4 Graphics
7.1 List Boxes and Combo Boxes
• A Review of List Box Features (Review)
• The Combo Box Control
• A Helpful Feature of Combo Boxes
List Box Properties
• lstBox.DataSource: The source of data to
populate the list box (ArrayName.ToList or QueryName.ToList)
lstOutput.DataSource = stateQuery.ToList
• lstBox.Items.Count: The number of items in the
list box
• lstBox.Sorted: If set to True, items will be
displayed in ascending ASCII order.
List Box Properties cont.
• lstBox.Items(n): The item having index n. It must
be converted to a string before being displayed in a
text or message box (data type is object)
txtBox.Text = CStr(lstBox.Items(1))
• lstBox.SelectedIndex: The index of the selected
item. If no item is selected, the value is -1
txtBox.Text=CStr(lstBox.Items(lstBox.SelectedIndex))
• lstBox.Text: The selected item as a string. It is
equivalent to Str(lstBox.Items(lstBox.SelectedIndex))
List Box Methods
• To delete the first occurrence of an item:
lstBox.Items.Remove(str)
LstBox.Items.Remove("Guan Yu")
List Box Methods(Cont.)
• To delete the first occurrence of an item:
lstBox.Items.Remove(str)
• To delete an item at a given location
lstBox.Items.RemoveAt(n)
• To remove all of the items from a list box
lstBox.Items.Clear()
List Box Methods(Cont.)
• To delete the first occurrence of an item:
lstBox.Items.Remove(str)
• To delete an item at a given location
lstBox.Items.RemoveAt(n)
• To remove all of the items from a list box
lstBox.Items.Clear()
• To append new item at the end in a list box
lstBox.Items.Add(str)
• To add new item at certain place.
lstBox.Items.Insert(index, str)
• To find the index of the first item to have the value
lstBox.Items.IndexOf(value) lstBox.Items.IndexOf("Liu Bei") is 2
lstBox.Items.IndexOf("Lü Bu") is -1
List Box Events
• Three main types of events with list boxes:
• Click – if the user clicks on an item in the list box
• SelectedIndexChanged - if the user clicks on an item
(even the same item) or uses the arrow keys to select it
• DoubleClick - if the user double-clicks on an item
• Click, DoubleClick, and SelectedIndexChanged
events are triggered when the user double-clicks.
MultiSelect with List Box
• SelectionMode property is used to set
multiple selection mode
None
One
MultiSimple
MultiExtended
MultiSelect with List Box
• SelectionMode property is used to set
multiple selection mode
None
One
MultiSimple
MultiExtended
• SelectedItems property returns a collection
lstBox.SelectedItems(n) n=0 Cao Cao,n=1 Sima Yi
• To get the number of the selected items
lstBox.SelectedItems.Count
Example(Multiselect)
Private Sub Button1_Click(…) Handles Button1.Click
If ListBox1.SelectedItems.Count <> 2 Then
MessageBox.Show("Please select two candidate's names.")
Else
TextBox1.Clear()
For i = 0 To ListBox1.SelectedItems.Count - 1
TextBox1.Text &= CStr(ListBox1.SelectedItems(i)) & ","
Next
End If
End Sub
Private Sub Button2_Click(…) Handles Button2.Click
Dim heroName As String
heroName = InputBox("Please input the new hero's name", "Input")
ListBox1.Items.Add(heroName)
End Sub
The Combo Box Control
• A list box combined with a text box
• The user has the option of filling the text
box by selecting from a list or typing
directly into the list box.
• Essentially same properties, events, and
methods as a list box.
DropDownStyle Properties of
Combo Box
• Combo Box has no SelectionMode property, but it has
DropDownStyle property sepecially
• Simple 简单组合框(不能下拉,可选也可自行输入)
• DropDown 下拉式组合框(可选也可自行输入)
• DropDownList 下拉式列表框(用户不能自行输入)
The Text property is the contents of the text box at the top
of the combo box
Helpful Feature of Combo Box
Each time a letter is typed into the text box at the top of
the combo box, the combo box will scroll to the item which
beginning with the letters you typed into it.
Comments and Exercises
Comments7.1 P269
Exercises7.1 P270
7-1-4
7-1-5 the combo box for brand is a DropDown combo
box, the other two are DropDownList combo boxes.
7.2 Eight Additional Controls
and Objects
•
•
•
•
•
The Timer Control
The Random Class
The ToolTip Control
The Clipboard Object
The Picture Box Control
• The MenuStrip Control
• The Horizontal and Vertical Scroll Bar Controls
The Timer Control
• Invisible during run time
• Raises an event called Timer1.Tick after a specified
period of time
• The Interval property specifies the time period measured in
milliseconds
• Enabled property is used to start or stop timing
• To begin timing, set Enabled property to True
• To stop timing, set Enabled property to False
Example 1: Timer Tick
Dim n As Integer 'FontSize
Dim factor As Integer 'Control the font size turn to large or small
Private Sub Form1_Load(…) Handles MyBase.Load
n = TextBox1.Font.Size
factor = 1 'Become larger by default
End Sub
Private Sub btnStart_Click(…) Handles btnStart.Click
Timer1.Enabled = True
End Sub
Private Sub btnPause_Click(…) Handles btnPause.Click
Timer1.Enabled = False
End Sub
Private Sub Timer1_Tick(…) Handles Timer1.Tick
n = n + 5 * factor
TextBox1.Font = New System.Drawing.Font("Arial", n)
If n >= 100 Then
factor = -1
ElseIf n <= 5 Then
factor = 1
End If
End Sub
Example: Exam Countdown
Private Sub btnStart_Click(…) Handles btnStart.Click
Dim Duration As String
Dim FinishTime As Date
Duration = InputBox("Please input the duration in minutes.", "Input Box", 120)
If Not IsNumeric(Duration) Then
MessageBox.Show("the duration is invalid!", "Message Box")
Else
txtNow.Text = FormatDateTime(TimeOfDay, DateFormat.LongTime)
FinishTime = TimeOfDay.AddMinutes(CInt(Duration))
txtFinish.Text = FormatDateTime(FinishTime, DateFormat.LongTime)
btnStart.Enabled = False
btnStop.Enabled = True
Timer1.Enabled = True
End If
End Sub
Example: Exam Countdown
Private Sub btnStart_Click(…) Handles btnStart.Click
Dim Duration As String
Dim FinishTime As Date
Duration = InputBox("Please input the duration in minutes.", "Input Box", 120)
If Not IsNumeric(Duration) Then
MessageBox.Show("the duration is invalid!", "Message Box")
Private Sub Timer1_Tick(…) Handles Timer1.Tick
Else
Dim H, M, S, Remain As Integer
txtNow.Text = FormatDateTime(TimeOfDay, DateFormat.LongTime)
txtNow.Text = FormatDateTime(TimeOfDay, DateFormat.LongTime)
FinishTime = TimeOfDay.AddMinutes(CInt(Duration))
Remain=DateDiff(DateInterval.Second,CDate(txtNow.Text),CDate(txtFinish.Text))
txtFinish.Text = FormatDateTime(FinishTime, DateFormat.LongTime)
H = Remain \ 3600
btnStart.Enabled = False
M = (Remain Mod 3600) \ 60
btnStop.Enabled = True
S = Remain Mod 60
Timer1.Enabled = True
txtRemaining.Text = H & ":" & M & ":" & S
End If
If Remain <= 0 Then
End Sub
Timer1.Enabled = False
MessageBox.Show("Finish.", "Message Box")
End If
End Sub
The Random Class
• A random number generator is declared with the
statement
Dim randomNum As New Random()
• If m and n are whole numbers and m < n then
the following generates a random whole number
between m and n (including m, but excluding n)
randomNum.Next(m, n)
Example 2 Winning Numbers
Private Sub btnSelect_Click(…) Handles btnSelect.Click
'Display the winning lottery number
Dim randomNum As New Random()
Dim num As Integer
txtNumbers.Clear()
For i = 1 To 3
num = randomNum.Next(0, 10)
txtNumbers.Text &= num & " "
Next i
End Sub
DC Lottery: District of Columbia’s Lottery 华盛顿哥伦比亚特区发行的彩票
The ToolTip Control
• Allows a tooltip to appear when user hovers over a
control (such as a text box)
• Text displayed in tooltip is the setting of the
“ToolTip on ToolTip1” property of the control to be
hovered over 这个属性是在每个需要显示tooltip的控件上设置的
• AutomaticDelay - determines the length of time (in
milliseconds) required for a tooltip to appear
• AutoPopDelay - determines the length of time the
tooltip remains visible while the cursor is stationary
inside the control这两个属性是在tooltip控件上设置的
Example 3: ToolTip Control
txtPrice
“ToolTip on ToolTip1” property of txtPrice has the setting “the Price without tax”
AutomaticDelay property of ToolTip1 has the setting 200
AutoPopDelay property of ToolTip1 has the setting 5000
The Clipboard Object
• Used to copy information from one place to another
• Maintained by Windows. It can even be used with
programs outside of Visual Basic
• A Clipboard Object is a portion of memory that has
no properties or events
• To place something into the Clipboard:
Clipboard.SetText(str)
• To get something out of the Clipboard:
str = Clipboard.GetText
• To delete the contents of the Clipboard:
Clipboard.SetText("")
The Picture Box Control
• Designed to hold drawings and pictures
• The graphics unit of measurement is called a pixel
• To get a feel for pixel measurement, place a picture
box on a form and look at the picture box’s Size
property. The two numbers in the setting give the
width and height of the picture box in pixels
The Picture Box Control Cont.
• Designed to hold drawings and pictures
• The graphics unit of measurement is called a pixel
• To get a feel for pixel measurement, place a picture
box on a form and look at the picture box’s Size
property. The two numbers in the setting give the
width and height of the picture box in pixels
• Each point in a picture box is identified by a pair of
coordinates, (x, y).
x pixels
y pixels
(x, y)
The Picture Box Control Cont.
picBox.Refresh()
• clears all graphics and text from the picture box
picBox.CreateGraphics.DrawLine(Pens.Red,
50, 50, 350, 150)
• draws a red line connecting the two points specified
by the coordinate pairs (50,50) and (350,150)
The Picture Box Control Cont.
picBox.CreateGraphics.DrawRectangle(Pens.Blue,
50, 50, 300, 100)
• draws a Blue rectangle specified by a coordinate
pair (50,50), a width 300 and a height 100
The Picture Box Control Cont.
picBox.CreateGraphics.DrawEllipse(Pens.Green,
50, 50, 100, 100)
• draws a Green ellipse specified by a coordinate pair
(50, 50) as the upper-left corner, and the horizontal
diameter 100 and vertical diameter 100
picBox.CreateGraphics.DrawRectangle(Pens.Blue, 50, 50, 300, 100)
picBox.CreateGraphics.DrawEllipse(Pens.Green, 50, 50, 100, 100)
The Picture Box Control Cont.
picBox.CreateGraphics.DrawEllipse(Pens.Green,
50, 50, 100, 100)
• draws a Green ellipse specified by a coordinate pair
(50, 50) as the upper-left corner, and the horizontal
diameter 100 and vertical diameter 100
picBox.CreateGraphics.DrawRectangle(Pens.Blue, 50, 50, 300, 100)
picBox.CreateGraphics.DrawEllipse(Pens.Green, 50, 50, 300, 100)
The Picture Box Control Cont.
• A picture can be placed in a picture box control with
the Image property at design time, or with code at
run time:
picBox.Image = Image.FromFile(filespec)
• SizeMode property is used to set how to show the
Image, the selections are the following:
•
•
•
•
•
Normal show picture at the upper-left corner of the picture box control
StretchImage will resize the picture to fit the picture box control
AutoSize will resize the picture box control to fit the picture
CenterImage will show the picture at the center of the picture box
Zoom will increase or decrease the picture to fit the picture box
maintaining the size ratio
picBox.SizeMode=PictureBoxSizeMode.AutoSize
The Horizontal and Vertical
Scroll Bars
• When the user clicks on one of the arrow buttons, the
scroll box moves a small amount toward that button
• When the user clicks between the scroll box and one of
the arrow buttons, the scroll box moves a large amount
toward that button
• The user can also move the scroll box by dragging it
• hsbBar.Value is between hsbBar.Minimum and
hsbBar.Maximum, and gives the location of the scroll
box.
Minimum
Maximum
Large Change
Value
(Small Change)
Scroll Bar Notes
• The setting for the Minimum property must be less
than the setting for the Maximum property
• The Minimum property determines the values for
the left and top arrow buttons
• The Maximum property determines the values for
the right and bottom arrow buttons
• The Scroll event is triggered whenever any part of
the scroll bar is clicked.
Adjust speed with Scroll Bar.
The MenuStrip Control
Used to create menus like the following
Top-level menu
Second-level menu
• Add new menu Item, set access key,
set shortcut key, add separator
• set enabled, visible, checked property
• Each menu item responds
to the Click event just like
a command button
• Click event can be triggered by
• the mouse
• Alt + access key
• Shortcut key.
Comments and Exercises
Comments7.1 P269
Exercises7.2 P282
7.3 Multiple-Form Programs
•
•
•
•
•
•
•
Startup Form
Scope of Variables, Constants, and Procedures
Modality
Close and ShowDialog Methods
The FormClosing Event Procedure
Importing an Existing Form
Deleting a Form from a Program
Multiple Forms
• VB programs can contain more than one form
• To add the new form, select Add Windows Form from the
Project menu, or right click the solution’s name in solution
explore window to invoke the Add New Items dialog box.
Multiple Forms (Cont.)
The new Form will appear
in solution explorer
select
Windows Form
type in name
press Add button
Startup Form
• The form that loads when the program starts running
is called the startup form.
• To designate a form as the startup form
1. Right-click the program name in Solution Explorer window
2. Click on Properties in the context menu
3. Select the form from the “Startup form” drop-down list.
Variables and Multiple Forms
• Variables declared in the Declarations section of a
form or a module(模块) with Public, instead of Dim,
will be available to all forms in the program. The
variable is said to have namespace-level scope
• So far, we have talked about four variable’s levels:
Block-Level
Local-Level
Class-Level
Namespace-Level
Variables and Multiple Forms
• When a Public variable is used in another form, it is
referred to by two ways:
If the variable is declared in a form, it will be referred to as
otherForm.variableName
If the variable is declared in a module, it may be referred to as
variableName
Methods of Form
frmOther.Show()
displays frmOther as a normal form
frmOther.ShowDialog()
displays frmOther as a modal form. An opening
modal form must be closed before the user can work
with any other form
frmName.Hide()
conceals(隐藏) the specified form
frmName.Close()
closes the specified form.
Events of Form
• Load event is raised before a form is displayed
for the first time. It is used to initializing the
values of some variables or other settings
• FormClosing event is raised before a form is
closed. Usually, It is used to save the result of
the form.
Importing an Existing Form
1. Click on Add Existing Item in Project menu.
2. Navigate to and open the folder for the form.
3. Double-click on formName.vb.
Note:
1. You will add a copy of the existing form
2. Text files must be copied separately
Example: Grade Analyzing
Example: Code
Comments and Exercises
Comments7.1 P269
Exercises7.3 P291
7-3-9 Write a program to analyze the final exam grades,
shown as following. There are three forms (frmMain,
frmInput, frmAnalyze) and a module in the solution.
Values are passed among the forms with
public variables declared in the module.
Hint: public variables declared in module can be used
in other forms with variable’s name directly.
7.4 Graphics
•
•
•
•
•
•
Graphics Objects
Lines, Rectangles, Circles, and Sectors
Pie Charts
Bar Charts
Animation
Printing Graphics (Self-Study)
Graphics Objects
• We have talked about the following statements:
picBox.Refresh()
picBox.CreateGraphics.DrawLine(Pens.Red, 50, 50, 350, 150)
picBox.CreateGraphics.DrawRectangle(Pens.Blue, 50,50,300,100)
picBox.CreateGraphics.DrawEllipse(Pens.Green, 50,50,100,100)
Dim gr As Graphics = picBox.CreateGraphics
declares gr to be a Graphics object for picBox, then
gr.DrawLine(Pens.Red, 50, 50, 350, 150)
gr.DrawRectangle(Pens.Blue, 50,50,300,100)
gr.DrawEllipse(Pens.Green, 50,50,100,100)
perform the same functions.
Graphics Objects Draw String
之前的Graphics Objects使用的是Pen.Color,下面学
到的用Brushes.Color
Dim gr As Graphics = picBox.CreateGraphics
gr.DrawString(string, Me.Font, Brushes.Color, x, y)
Displays string in the picBox. The upper-left corner of the text
has coordinates (x, y), the font used is the Form’s font, and
the color of the text is specified by color. For Example:
Dim gr As Graphics = picBox.CreateGraphics
Dim s As String = "Hello"
gr.DrawString(s, Me.Font, Brushes.Blue, 5, 30)
gr.DrawString("World",Me.Font, Brushes.Red, 35, 50)
Graphics Objects Draw Solid Rectangle
Dim gr As Graphics = picBox.CreateGraphics
gr.FillRectangle(Brushes.Color, x, y, w, h)
draws a solid rectangle of width w and height h in the
color specified and having the point with coordinates (x, y)
as its upper-left corner
picBox.CreateGraphics.FillRectangle(Brushes.Blue, 50, 50, 300, 100)
OR:
Dim gr As Graphics = picBox.CreateGraphics
gr.FillRectangle(Brushes.Blue, 50, 50, 300, 100)
Graphics Objects Draw Solid Ellipse
Dim gr As Graphics = picBox.CreateGraphics
gr.FillEllipse(Brushes.Color, x, y, w, h)
draws a solid ellipse in the color specified inscribed in (内切于)
the rectangle described by the values x, y, w, and h
Note: When w = h, the ellipse is a circle
picBox.CreateGraphics.FillEllipse(Brushes.Blue, 50, 50, 300, 100)
OR:
Dim gr As Graphics = picBox.CreateGraphics
gr.FillEllipse(Brushes.Blue, 50, 50, 300, 100)
Graphics Objects Draw Solid Circle with
Center and Radius..
Dim gr As Graphics = picBox.CreateGraphics
gr.FillEllipse(Brushes.Color, x-r, y-r, 2*r, 2*r)
draws a solid circle in the color specified with center (x, y) and
radius r
picBox.CreateGraphics.FillEllipse(Brushes.Blue, 200-50,100-50,2*50,2*50)
OR:
Dim gr As Graphics = picBox.CreateGraphics
gr.FillEllipse(Brushes.Blue,200-50,100-50,2*50,2*50)
Graphics Objects Draw Sector
Dim gr As Graphics = picBox.CreateGraphics
gr.FillPie(Brushes.Color, x-r, y-r, 2*r, 2*r, StartAngle, SweepAngle)
draws a solid sector of a circle with center (x, y), radius r, and
having the specified startAngle and sweepAngle. The color of
the sector is determined by the value of Color
注意:这里直接采用角度(degree),而不是弧度(radian)!
Brushes, Pens, and Fonts
Variables can be used for brushes, pens, and fonts. For example
the statement
gr.FillRectangle(Brushes.Blue, 50,50,300,100)
can be replaced with
Dim br As Brush = Brushes.Blue
gr.FillRectangle(br, 50, 50, 300, 100)
gr.DrawRectangle(Pens.Blue, 50,50,300,100)
can be replaced with
Dim pen As Pen = Pens.Blue
gr.DrawRectangle(pen, 50, 50, 300, 100)
gr.DrawString("Hello China!", Me.Font, Brushes.Green, 50, 50)
can be replaced with
Dim myFont As Font = New Font("simhei", 40)
gr.DrawString("hello China!", myFont, Brushes.Green, 50, 40)
Single Data Type
• Numeric variables used in Draw and Fill statements
must be of type Integer or Single
• The Single data type is similar to the Double type,
but has a smaller range (-3.4×1038~3.4×1038)
• CSng converts other data types to the Single data
type. For Example: Dim a As Single = CSng(TextBox1.Text)
Dim b As Single = CSng(10/3)
.
Financing Public Schools Data
Amount
Percent angle
(in billions)
Federal $33
8%
0°~28.8°(360×8%)
State
$206
49%
28.8°~28.8+176.4°(360×49%)
Local
$180
43%
205.2°~205.2+154.8°(360×43%)
Draw Pie Chart
205.2
Dim gr As Graphics = picBox.CreateGraphics
gr.FillPie(Brushes.Blue, 5, 5, 200, 200,0, 28.8)
gr.FillPie(Brushes.Red, 5, 5, 200, 200, 28.8, 176.4)
gr.FillPie(Brushes.Tan, 5, 5, 200, 200, 205.2, 154.8)
154.8
176.4
28.8
0
28.8
205.2
Create the Pie Chart
154.8
176.4
28.8
0
28.8
Dim gr As Graphics = picBox.CreateGraphics
Dim p() As Single = {.08, .49, .43} 'percent of each angle
Dim br() As Brush={Brushes.Blue,Brushes.Red,Brushes.Tan}
Dim startAngle As Single = 0
gr.FillPie(br(0), 5, 5, 200, 200, startAngle, p(0)*360)
startAngle += p(0) * 360
gr.FillPie(br(1), 5, 5, 200, 200, startAngle, p(1)*360)
startAngle += p(1) * 360
gr.FillPie(br(2), 5, 5, 200, 200, startAngle, p(2)*360)
startAngle += p(2) * 360
.
205.2
Create the Pie Chart
154.8
176.4
28.8
0
28.8
Dim gr As Graphics = picBox.CreateGraphics
Dim p() As Single = {.08, .49, .43} 'percent of each angle
Dim br() As Brush={Brushes.Blue,Brushes.Red,Brushes.Tan}
Dim startAngle As Single = 0
For i As Integer = 0 To 2
gr.FillPie(br(i), 5, 5, 200, 200, startAngle, p(i)*360)
startAngle += percent(i) * 360
Next
Financing Public Schools Bar Chart
• Suppose the x-axis is 110 pixels below the top of
the picture box
• Let the unit for the rectangle heights be .5 pixels
• Then the top of a rectangle corresponding to the
quantity 33 is 110 – 33/2 pixels from the top of the
picture box.
Create the Bar Chart
Private Sub btnDisplay_Click(…) Handles btnDisplay.Click
Dim quantity() As Single={33,207,180} '联邦、州、本地对公立学校投入的教学经费
Dim gr As Graphics = picOutput.CreateGraphics '图形对象
'The picture box has width 210 and height 150
gr.DrawLine(Pens.Black, 40, 110, 210, 110) 'x-axis
gr.DrawLine(Pens.Black, 40, 110, 40, 0) 'y-axis
gr.DrawLine(Pens.Black, 35, 60, 45, 60) 'tick mark; 60=110-(100/2)
gr.DrawString("$100", Me.Font, Brushes.Black, 5, 55)
For i As Integer = 0 To quantity.GetUpperBound(0)
gr.FillRectangle(Brushes.Blue, 60+i*40, (110-quantity(i)/2), 20, quantity(i)/2)
Next
gr.DrawString("Federal State Local", Me.Font, Brushes.Black, 45, 115)
gr.DrawString("(Expenditures in billions)", Me.Font, Brushes.Black, 35, 125)
End Sub
Animation
One way to produce animation on a form is to place
an image into a picture box and then move the picture
box by regularly changing the location of the picture
box.
Flying Airplane
Private Sub btnStart_Click(…) Handles btnStart.Click
Timer1.Enabled = True
End Sub
Private Sub btnPause_Click(…) Handles btnPause.Click
Timer1.Enabled = False
End Sub
Private Sub Timer1_Tick(…) Handles Timer1.Tick
PictureBox1.Left += 5
If PictureBox1.Left >= Me.Width - PictureBox1.Width Then
PictureBox1.Left = -1 * PictureBox1.Width
End If
End Sub
Bouncing Ball..
Dim x As Integer = 1
Dim y As Integer = 1
Private Sub Timer1_Tick(…) Handles Timer1.Tick
picBall.Left += x
picBall.Top += y
If picBall.Left <= 0 Or picBall.Left >= (Me.ClientSize.Width - picBall.Width) Then
x = -x
End If
If picBall.Top <= 0 Or picBall.Top >= (Me.ClientSize.Height - picBall.Height) Then
y = -y
End If
End Sub
Comments and Exercises
Comments7.4 P302
Exercises7.4 P303
Example 7-4-1 Draw Pie Chart
Example 7-4-3 Bouncing Ball