Visual Basic 3 Some new components Some new capabilities OOD/OOP.

65
Visual Basic 3 Some new components Some new capabilities OOD/OOP
  • date post

    21-Dec-2015
  • Category

    Documents

  • view

    218
  • download

    1

Transcript of Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Page 1: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Visual Basic 3

Some new components

Some new capabilities

OOD/OOP

Page 2: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Index of projects covered in this ppt

• Date time display• Format currency• Form with picture box, group boxes,

radiobuttons• Flags of the world (more picture boxes, images)• Another picturebox/radiobutton example• Images from file example with combobox• Changing fonts using current property settings or

font “literal” values

Page 3: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Some points about class programming practices

• Try to use conventional names in your projects. It will make them easier to edit and code

• Some of you need more practice with arithmetic and with using data supplied in a textbox. You may need to take time outside of class to work on optional exercises or class projects.

• Note: If you don’t show me your labs or projects, I do not mark them as complete. It is your responsibility to make sure I see your completed work. If I haven’t seen your project during the class period, show me after class – I have office hour then. If you are not sure if I marked you come see me (F239) during office hour or email me which lab or project you want to know about.

Page 4: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Some points about class programming practices

• Your text, section 3.3 goes over how to perform calculations with numbers.

• Read this section of the text and do the exercises.

• Complete the operator practice form from the last slideshow.

Page 5: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

An aside: Foreground and background colors

• Users do best with grayscale coloring. But you can modify foreground and background color settings. In the form’s properties select backcolor….

Page 6: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Select custom, web or system

Page 7: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Select a color from the palette

Page 8: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Declaring/initializing variables

• Variables are declared using dim in VBDim name as StringDim value as IntegerDim val,num,x,y,z as Double• You can initialize variable values when

you declare them, as inDim value as integer =100Dim name as String =“Bob”

Page 9: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

You can declare constants

• Const pi as double=3.1412• Const ourbusiness as String=“VB Inc”• Const basehours as single=40.0• Constants may not be altered by assigning them

a new value later in your program. Typically, they would be declared at the class level (not discussed yet), just below the line at the top of your code view

Public class…

‘ put Global vars and consts here

Page 10: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

A date literal

• Date literals must appear within # symbols.

• They may contain date, time or both• Example formats:#12/10/2006##3:13 PM##21:15:02# ‘military#12/10/2006 3:13 PM#

Page 11: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Conversions for date

• You can convert date format values or strings to date type as in

Dim startdate, thedate as date

Dim stringval as string = “12/3/2005”

Startdate= #12/3/2005 1:00:00 AM#

thedate=System.convert.todatetime(stringval)

Page 12: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Formatting dates as Strings for display

• Dateformat.generaldate() will return “dd/mm/yyyy” if the date is just a date, otherwise see below for longtime

• Dateformat.longdate gives day of week, month and day, no time returned as in “Saturday, August 10, 2005”

• Dateformat.shortdate formats as in general date above, no time is reported.

• Dateformat.longtime does not report date part, but gives time in long format as in “03:22:18 PM”

• Dateformat.shorttime returns military time in format “HH:MM”• Access functions as:lblDateInfo.text=FormatDateTime(someDate,DateFormat.shorttime)

Page 13: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Form to display current date/time on load

Page 14: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Date literals

• Now returns the current day and time

• Today returns the current day (no time)

• TimeOfDay returns the current time, no date.

Page 15: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Onload code for previous form

Private Sub frmDayTime_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

Dim thedate As Date thedate = Today lbldate.Text = FormatDateTime(thedate,

DateFormat.LongDate) lbltime.Text = FormatDateTime(thedate,

DateFormat.LongTime) End Sub

Page 16: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Percent formatting

• You can format reals (single, double, decimal or literal values) as strings with percent format using the formatpercent() function:

FormatPercent(.789) will return “78.9%”FormatPercent(.48129) will return “48.13%”FormatPercent(8.2) will return “820.00%”FormatPercent(.3876,1) will return “38.7%”• Note the following: it multiplies parameter by 100

and then does a toString(). The default number of percentage places is 2.

Page 17: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Currency formatting

• Real values can be formatted as currency using toString(“C”) or FormatCurrency

Page 18: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Button click code

Private Sub btndisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btndisplay.Click

Dim value As Single = Single.Parse(txtvalue.Text) lbldisplay1.Text = lbldisplay1.Text & ":" & value.ToString("C") lbldisplay2.Text = lbldisplay2.Text & ":" &

FormatCurrency(value.ToString()) End Sub

Page 19: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Let’s build a new form

Page 20: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

After clicking the image, typing new text and selecting a radiobutton

Page 21: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

New components are groupbox, radiobutton and picturebox

• You’ll find these new components are pretty easy to use. From the toolbox:

• Select a groupbox and drop it on your form.

• Now drop 3 radiobuttons into the groupbox.

• Drop a picturebox on your form.• And another, right on top of the first.• Add two labels and a textbox.

Page 22: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Set properties• Our text uses radXXX to name radioButtons. I noticed another text

used names like greenRadioButton and inputTextBox. I will allow you to follow that convention if you wish.

• I also noticed our text leaves default names for controls which are not accessed in subroutines, though you’ll have to be careful. I will also allow you to follow this example.

• You should not generally need to reference groupboxes, or even labels, unless the text on them is used for result-display purposes.

• I left my groupbox and pictureboxes with their default names.• Name your labels and textbox and set their text properties.

Page 23: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

properties

• I set the font of my lblMessage to be symbol (greek).

• For each picturebox, I selected the image property and then clicked the (…) to open a Select Resource Dialog Box and browsed my system to find some images.

Page 24: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Setting the image

Page 25: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

What functionality do we want?

• Radiobuttons should change the color of the displayed text (in lblMessage).

• Since these are in a groupbox, VB will handle the exclusionary aspect of the functionality.

• When one image is clicked, I want it to go away and the other to be displayed.

Page 26: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Tab ordering when using group boxes

• Group boxes get tab ordering relative to other controls on your form, then controls inside a group box are ordered relative to each other.

Page 27: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Subroutines needed

Click on a radiobutton and provide code like messageLabel.ForeColor = Color.Green

to the stubbed subroutine. Here’s a complete example:

Private Sub greenRadioButton_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles greenRadioButton.CheckedChanged

messageLabel.ForeColor = Color.Green

End Sub

Page 28: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Coming attractions… a problem with the code in the previous slide

Green radio button “checked changed” event is fired when green radiobutton is selected or unselected. The code in the previous slide works because, when blue (for example) is selected, first green rb checked changed event is fired, then blue rb checked changed is fired, so the user’s current choice is updated properly. We’ll learn in a couple of weeks how to improve the event handler code to check whether the rb is CURRENTLY checked with a control structure called if… then:

If greenradiobutton.checked then messageLabel.ForeColor = Color.GreenEnd if

Page 29: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Subroutines needed

• Click a picturebox. Add code like this to one stubbed method (and the opposite code to the other):

PictureBox2.Visible = FalsePictureBox1.Visible = True

• Here’s one of the two complete subroutines:Private Sub PictureBox2_Click(ByVal sender As

System.Object, ByVal e As System.EventArgs) Handles PictureBox2.Click

PictureBox2.Visible = False PictureBox1.Visible = True End Sub

Page 30: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

OOP: Classes and variable scope

• Classes consist of fields, constructors and methods.

• In VB, methods are called subs.• Fields are variables declared at the top of the

class, visible to all the subs and functions in the class. Such variables should not be redefined in a sub – they are already available.

• We have already been using class fields, like txtinput.text and methods, like txtinput.clear() or me.close() in our examples.

Page 31: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

variable scope

• Parameters to functions and subs have local scope. They live only within the sub or function and are not available elsewhere.

• VB defines your controls for you (in hidden code). They are fields of the class and have global scope.

• Variables dimensioned inside subs and functions also have local scope and can’t be referenced outside the sub or function containing the definition.

Page 32: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

variable scope

• A variable which needs to be accessed in many subs will need to be passed to each, or declared as a class field.

Page 33: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Illustrating OOP: Flags of the world

Page 34: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

About this app

• The Flags project contains checkboxes, radiobuttons, one picturebox and groupboxes.

• Only checkboxes are new for us.

• But: updating the display involves putting a new image on the picture box, and changing the text in the country label.

Page 35: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

About this app

• We’ll need to be able to “get images” from files.

• We’ll need to keep track of the current country.

• Since multiple subs need to update the display we will create our own sub called updateDisplay.

• What parameters does updateDisplay need?

Page 36: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

What parameters does updateDisplay need?

• There are –as usual- many ways of doing it.

• The simplest might be to have a (class) field value (String) which holds the current country name. We’ll call it country. The code

• Dim country as String goes near the top of our code, but after the start of the class definition

Page 37: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Controls and their properties

• Not following VB convention, I named radiobuttons USARadioButton (etc)

• In their properties, I set initial visibility of my two labels to false.

• I initialized country string and flaglabel text to “USA”.

• Flaglabel text is initialized in properties.• Country is initialized in the class

constructor after the call to super.

Page 38: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

the constructor

Public Sub New()

MyBase.New() country = "usa“ ‘must go here since it is displayed 'This call is required by the Windows Form Designer. InitializeComponent()

'Add any initialization after InitializeComponent() call

End Sub

Page 39: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

More about this app

• We’ll need to get images from files. To do this we need to import some capability we haven’t used yet: System.io. The code:

• Import system.io goes right at the top of our code.

• Each radiobutton event handler just changes the name of the current country and calls the sub updateDisplay() passing it the country name.

• The checkbox event handlers simply set labels to visible or invisible based on whether they themselves are checked.

Page 40: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Code for one of the radiobuttons

Private Sub SwedenRadioButton_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SwedenRadioButton.CheckedChanged

updateDisplay("Sweden") ‘that is all we need to do

End Sub

Page 41: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Code for updateDisplay

Private Sub updateDisplay(ByVal countryname As String)

country = countryname ‘update field value

flagLabel.Text = country

‘need to get another image…glue on country name

MyPictureBox.Image = Image.FromFile(Directory.GetCurrentDirectory & country & ".gif")

End Sub

Page 42: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Code for one of the checkbox clicked event handlers

Private Sub countryCheckBox_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles countryCheckBox.CheckedChanged

‘set flaglabel visibility to true or false depending on ‘the checkbox setting

flagLabel.Visible = countryCheckBox.Checked

End Sub

Page 43: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Image files

• You’ll need to copy whatever flag images you want into the current project directory.

• You’ll need to give them names like “binUSA.gif”• VB attaches the “bin” to the front of the file name

when you get the directory in the debugger, but not when it is run as an exe file.

• To deploy the app as an executable you’ll have to fix the path name for the flag gif files and possibly copy the gif files to wherever the application is supposed to run from.

Page 44: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Exercise: Digit extraction

• Allow the user to enter a five-digit number.

• Display the digits, each in its own read-only textbox.

• Provide Enter and Clear buttons.

Page 45: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

GUI

Page 46: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Notes

• Make the output textboxes read only.

• Set the maximum length property of the input textbox to 5.

• Use layout managers to get the alignments and sizes right.

• Use the mod operation to get the “one’s place” value. Then use the \ operation to go on to the next digit.

Page 47: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Notes

• You could provide this functionality many ways.

• Later in the semester we’ll learn to do it by chopping the input string up into pieces 1 character long each.

Page 48: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Another exercise: Message formatter

Page 49: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Radio buttons control color

Private Sub rbRed_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rbRed.CheckedChanged

Me.lblMessage.ForeColor = Color.Red

End Sub

Page 50: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Checkbox determines if message should be displayed

Private Sub cbMessage_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cbMessage.CheckedChanged

Me.lblMessage.Visible = cbMessage.Checked

End Sub

Page 51: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Button click may display message

Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClear.Click

With Me With .txtName .Clear() .Focus() End With .txtMessage.Clear() .lblMessage.Text = "" End With End Sub

Page 52: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Click on picturebox to toggle picure box display

Page 53: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Pictureboxes’ event code Private Sub pbBig_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles pbBig.Click pbBig.Visible = False pbLittle.Visible = True

End Sub Private Sub pbLittle_Click(ByVal sender As System.Object, ByVal e

As System.EventArgs) Handles pbLittle.Click pbLittle.Visible = False pbBig.Visible = True

End Sub

Page 54: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Getting images

Page 55: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

More on images and fonts

Page 56: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Combobox & image.fromFile

Page 57: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Combo box• Select the collection property to populate the combo box• I usedPicturebox.image=image.fromfile(“C:\penguin.gif”);• My combobox selected index changed sub code is below:If cbbchoose.Text = "dog" Then pb.Image = Image.FromFile("c:\dog.gif")

ElseIf cbbchoose.Text = "bear" Then pb.Image = Image.FromFile("c:\bear.gif")

Else pb.Image = Image.FromFile("c:\penguin.gif") 'pb.Refresh() End IfNote: I didn’t take time to figure out how to get it to look in the application

directory

Page 58: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Changing fonts via button press

Page 59: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

I didn’t figure out how to get a font literal in this application

Page 60: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

code Private Sub btnfont3_Click(ByVal sender As System.Object, ByVal e

As System.EventArgs) Handles btnfont3.Click lbldisplay.Font = btnfont3.Font() End Sub

Private Sub btnfont1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnfont1.Click

lbldisplay.Font = btnfont1.Font() End Sub

Private Sub btnfont2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnfont2.Click

lbldisplay.Font = btnfont2.Font() End Sub

Page 61: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Literal font names

Page 62: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Press button to change font

Page 63: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

codePrivate Sub btn3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

Handles btn3.Click Dim f As New System.Drawing.Font("Arial", 10) ' Assign the font to the control lbl1.Font = f ' To set additional properties, you must create a new Font object. lbl1.Font = f 'lbl1.Font = New System.Drawing.Font(lbl1.Font, FontStyle.Bold Or FontStyle.Italic) End Sub Private Sub Btn2_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles Btn2.Click Dim f As New System.Drawing.Font("Symbol", 12) lbl1.Font = f ' or use... 'lbl1.Font = New System.Drawing.Font(f, FontStyle.Bold) End Sub Private Sub btn1_Click(ByVal sender As System.Object, ByVal e As

System.EventArgs) Handles btn1.Click Dim f As New System.Drawing.Font("SansSerif", 12) lbl1.Font = f lbl1.Font = New System.Drawing.Font(lbl1.Font, FontStyle.Underline) End Sub

Page 64: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Image.fromfile(“P:\...”) does work in F306 lab: a screenshot

Page 65: Visual Basic 3 Some new components Some new capabilities OOD/OOP.

Code for previous slide

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

PictureBox1.Image = Image.FromFile("p:\africa1.jpg")

End Sub