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

Post on 21-Dec-2015

218 views 1 download

Tags:

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

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

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.

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.

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….

Select custom, web or system

Select a color from the palette

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”

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

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#

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)

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)

Form to display current date/time on load

Date literals

• Now returns the current day and time

• Today returns the current day (no time)

• TimeOfDay returns the current time, no date.

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

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.

Currency formatting

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

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

Let’s build a new form

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

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.

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.

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.

Setting the image

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.

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.

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

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

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

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.

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.

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.

Illustrating OOP: Flags of the world

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.

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?

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

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.

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

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.

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

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

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

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.

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.

GUI

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.

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.

Another exercise: Message formatter

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

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

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

Click on picturebox to toggle picure box display

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

Getting images

More on images and fonts

Combobox & image.fromFile

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

Changing fonts via button press

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

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

Literal font names

Press button to change font

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

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

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