Az előadás letöltése folymat van. Kérjük, várjon

Az előadás letöltése folymat van. Kérjük, várjon

Objektum Orientált Programozás

Hasonló előadás


Az előadások a következő témára: "Objektum Orientált Programozás"— Előadás másolata:

1 Objektum Orientált Programozás
Visual Basicben

2 Objektumok Object – egy dolog, tárgy, „valami” Jellemzők Viselkedés
Command button, text box, stb. Jellemzők Properties – tulajdonságok, adatok, változók Caption, text, listindex Viselkedés Method – cselekvés, akció, eljárások, függvények Clear, movenext, additem Events – az objektum válaszai a felhasználó cselekvésére vagy más eseményre (automatikusan kiváltódó metódusok) Click, got focus, activate

3 Osztály modul Új objektum típusokat, azaz osztályokat az osztály modulban készíthetünk Project, Add Class Module "C" prefixum használatos Az osztály modulban fogjuk definiálni a Properties Methods Events

4 Osztályok és példányok
Az eszköztár elemei osztályokat reprezentálnak Valójában az osztályok egy példányát adjuk a programunkhoz, amikor a tool box-ból választunk Pl. minden textbox a formon a textbox osztály egy példánya Használd az Object Browser (F2) hogy lásd az osztályokat és a hozzájuk tartozó tulajdonságokat (Properties), metódusokat (Methods) és eseményeket (Events) Vegyük észre, hogy az osztály azonos szerepet tölt be, mint a típus, az objektum pedig mint a változó Text1 pl. szövegdoboz típusú „változó”

5 Objektum Orientált Terminológia
Encapsulation (Egybezártság) A tulajdonságok és a metódusok egységbe vannak zárva Az objektummal csak azt tudjuk megtenni, amit az objektum tud (kérni lehet, manipulálni nem) Az adatait nem láthatjuk közvetlenül

6 Objektum Orientált Terminológia
Polymorphism (Többalakúság) Különböző osztályok ugyanolyan névvel tartalmazhatnak komponenseket, de ezek különbözhetnek egymástól A programozók az objektum vagy a végrehajtás pontos ismerete nélkül tudnak kérni cselekvéseket az objektumoktól Pl. Debug.Print, Printer.Print

7 Objektum Orientált Terminológia
Inheritance (Öröklődés) Létező osztályokból származtathatóak új osztályok VB6 ezt nem tudja…. Tehát nem „igazi” OOP (Object Oriented Programming) A VB.Net már igen (2001)

8 Objektum Orientált Terminológia
Reusability (Újrafelhasználhatóság) Az öröklődés hátsószándéka VB nem teljesen engedi, de: Delegáció ÉS Superclasses-olyan osztályok, melyek osztott kódjait elérhetjük

9 Objektum Orientált Terminológia
Jellemzők Tulajdonságokként jelenik meg A tulajdonságokat változókkal adjuk meg az osztálymodulban Viselkedés Metódusokként jelenik meg A metódusokat eljárásokkal és függvényekkel adjuk meg az osztálymodulban

10 Új osztály létrehozása
Project, Add Class Module

11 Az osztály tulajdonságai
A Class Module-n belül a General Declarations-ban adjuk meg Ne használjuk a Public módosítót, sértjük vele az encapsulation elvet (minden objektum felelőséggel kell hogy tartozzon a saját adatai tekintetében) Private tulajdonságnév as típus

12 Értékek hozzárendelése a tulajdonságokhoz
Speciális eljárásokkal történik (Tools, Add Procedure,Property) Értékek átadása a class module-nak Értékek átvétele a class module-ból Property Let procedure Tulajdonságok beállítására Property Get procedure Tulajdonságok átvételére Muszáj visszaadni egy értéket (függvény) Külső tantárgyi koncentráció: A papagájnak muszáj zsivajogni!!!!

13 Property Get Property Get PNév ([paraméterek] [As Típus] ) Utasítások
PNév=TulajdonságNév End Property Például: Property Get LastName () as String LastName=mstrLastName A Class modulban generálva az általános deklarációs részben

14 Property Let Property Let PNév([paraméterek] érték [As Típus] )
Utasítások TulajdonságNév=érték End Property Example: Property Let LastName (strLastName as String) mstrLastName=strLastName

15 Példányosítás: Dim objnév as New osztálynév (General Declarations)
Dim objnév as osztálynév . Set objnév=New osztálynév (Pl. Form_Load)

16 Példányosítás: Dim|Public|Private objnév As New osztnév
Dim mEmployee As New CEmployee Private mInventory As New CInventory Vagy Dim mEmployee As CEmployee Set mEmployee=New CEmployee Private mInventory As CInventory Set mInventory=New CInventory

17 Erőforrások felszabadítása
Form_Unload-ban Set mEmployee = Nothing

18 Inicializáló és termináló események
Minden Class Module rendelkezik két előredefiniált eseménnyel: Class_Initialize Amikor egy objektum létrehozódik Class_Terminate Amikor egy objektum „Nothing”-gé válik Kilép a láthatóságból (pl. lokális változóként volt jelent)

19 Esemény generálás Objektum által Lehetnek (Click, MouseUp, stb)
Esemény létrehozó Eseményt lekezelő (Click, MouseUp, stb)

20 Reagálás az eseményekre
Az eseményekre való reagálás szerint az objektumok lehetnek Termelő Csökkentő Examples of events we are used to seeing as responding cmdOK_Click form_MouseUp

21 Event Examples User clicks a command button
Event Source(Provider)=the Command Button Form module's command button's click event executes Event Sink(Consumer)=Form

22 How to generate an event
Declare the event in the General Declarations section of the class module, pass arguments with an event if you wish Public Event TaskComplete( ) Raise the event in code in the same module the Event was delcared in If mblnJobFinished Then RaiseEvent TaskComplete End If

23 How to respond to an event
Declare the object using WithEvents Private WithEvents mMyTask as CMyTask Instantiate the object using Set Set mMyTask=New CMyTask Write the code for the event procedure When finished release the object variable using Nothing keyword

24 Collections A Collection Class holds references for a series of objects created from the same class or from different classes Actually a collection holds references to the objects You reference by Index Number or a Key Similar to list box and the associated items in the list box

25 Key for Collection Objects
Key must be a string Can be used to reference individual objects in the collection Declare the Key as String at the module level of the Class module for the object (not the collection) Add Property Get and Let procedures

26 Creating a Collection Create a new class module
Name it as plural of the objects in the collection CProducts is a Collection of CProduct objects Declare an object variable "As Collection" (in Gen Declarations) and VB automatically provides: Add, Remove, and Item methods Count property

27 Creating a collection cont.
Code the Class_Initialize Event Set equal to New Collection Code the Class_Terminate Event Set equal to Nothing Code the private function that calculates the next Item number and/or assigns the Key

28 Creating a collection cont.
Code the Add Wrapper Event to add items to the collection Code the Remove Wrapper Event to remove items to the collection Code Item Wrapper Event to access individual elements in the collection Write Property Get and Let for the Count property of the collection

29 Állomány kezelés

30 Állományok Az állományok háttértárolón vannak Adatokat tartalmaznak
Rekordok ==> Sorok Mezők ==> Adat elemek a sorokon belül

31 Szekvenciális A rekordok vége CR, a file vége EOF
A mezők vesszővel vannak elválasztva Változó hossz Sztringek idézőjelek között (a számok nem) Csak sorosan olvasható Minden előző mezőt el kell olvasni az eléréshez

32 Példa "Lynne","Weldon","999 Wide Way","Aiken","SC","29803" <CR>
"Jim","Buck","1 Cow Lane","Aiken","SC","29801" <CR> "Tom","Thumb","PO Box 200","Aiken","SC"," " <EOF>

33 Random A rekordok azonos hosszúságúak, van hivatkozási számuk
A mezők fix hosszúak és pozíciójúak A hossznál kisebb adatok szóközökkel kiegészítődnek A nagyobbak csonkolódnak Tetszőleges sorrendben olvasható/írható Táblázatszerűen képzelhető el

34 Példa

35 Kezeléseik Open file Read, Write Close file

36 Open Statement Általában a Form_Load-ban
Open „elérésiút_állománynév" For {Input|Output|Append|Random} As #FileSorszám [Len=hossz] FileSorszám = 1 to 511, hossz Max = 32,767 A hosszú elérési út helyett helyezzük az aktuális projekt alkönyvtárba az állományunkat, majd használjuk a App.Path kifejezést.

37 Open For Input Output Append Random olvasásra
Írásra, BOF-t helyez el, majd felülír Append Az EOF-tól kezd írni Random Közvetlen elérésű állományokat olvas/ír

38 Példák Sequential Random Open "C:\VB6\myfile.txt " For Input As #6
Open "A:\myfile.txt " For Output As #1 Open App.Path & “\myfile.txt " For Append As #2 Random Open "A:\myfile.txt " For Random As #3 Len=60

39 File elérési útja Probléma: Az Open minősített teljes elérést kíván
Vagy Minden állomány a projekt alkönyvtárban App.Path Dim strPath as String strPath=App.Path & "\Filename.extension" Open strPath for Input as #4 Common Dialog használata ShowOpen metódussal

40 Azaz.. With dlgCommon Dim strFileName as String .DialogTitle = "Open"
.CancelError = False .Filter = "All Files (*.*)|*.*" .ShowOpen If Len(.FileName) = 0 Then Exit Sub End If strFileName=.FileName End With Open strFileName for Input as #1

41 A Close utasítás Fájl lezárása Általános helyei: Close [#FileNumber]
Form_Unload, mnuFileSave, mnuFileSaveAs, mnuFileExit Close [#FileNumber] Ha a FileNumber hiányzik, akkor minden nyitott fájl (Az END is lezár, de nem helyes)

42 Példák Close #6 Close #1, #3 Close

43 FileNumber FreeFile Függvénnyel A rendszer adja Előnyei
Nincs összeakadás más alkalmazásokkal Nem kell nyilvántartani Dim intFileNumber as Integer intFileNumber=FreeFile Open "Names.txt" For Output As #intFileNumber

44 Szekvenciális állományok

45 Olvasás Open for Input Input utasítással olvasunk

46 Input Általában a Form_Load-ban Do Until EOF
Input #FileNumber, List of variables Input #2, strCourseNum, strClass, intHours

47 Input Dim strVideoTitle as String Do Until EOF(3)
Input #3, strVideoTitle cboVideoTitle.AddItem strVideoTitle Loop Figyelem, számegyezés!!

48 Write Open For Output!! Általános helyei: Close-zal zárul
mnuFileSave, mnuFileClose , Form_QueryUnload Close-zal zárul

49 Write Példa Write #FileNumber, List of variable or fields
Write #1, txtFirstName, txtLastName, txtStreet, txtCity, txtxState, txtPhone Write #2, strCourseNum, strClass, intHours

50 Write For…. Next Dim intIndex as Integer
Open "A:\videos.txt" For Output As #1 For intIndex=0 to cboVideoTitle.ListCount-1 Write #1, cboVideoTitle.ListIndex Next intIndex Close #1

51 Törlés Kill utasítás Nem lehet nyitva Kill „elérésiút"
Kill "A:\Names.txt"

52 Átnevezés Name utasítás Nem lehet nyitva
ReName „régi_elérés" As „Újelérés" ReName "A:\Names.txt" As "A:\People.txt"

53 Átírás Vátoztatások mentése Open eredeti for Input
Open temp file for Output Beolvasás pl. textboxba az eredetiből Kiírás textboxból a temp-be Close Kill eredeti Name temp

54 Új létrehozása Open név for Output Ha nincs, létrehozza
Kiírás az áll-ba Close

55 Közvetlen elérésű állományok

56 Random A rekordok azonos hosszúságúak, van hivatkozási számuk
A mezők fix hosszúak és pozíciójúak A hossznál kisebb adatok szóközökkel kiegészítődnek A nagyobbak csonkolódnak Tetszőleges sorrendben olvasható/írható Táblázatszerűen képzelhető el

57 Példa

58 Rekord struktúra definiálása
Még mielőtt I/O történik Type/End Type Helye: General Declarations Fix hosszúságú sztringeket alkalmazzunk!! Pl: Dim strFName as String * 20

59 Type/End Type Private Type Person intEmpNum As Integer
strFName As String * 20 strLName As String * 30 strPhone As String * 12 curRate As Currency End Type Dim mudtPersonRecord As Person Open App.Path & "\Names.dat" For Random as #1 Len=Len (mudtPersonRecord) Lehetőség: mudt prefix a User Defined Type-hoz….

60 Open Open után lehet írni, olvasni is
Ha nem létezőt nyitunk, létrehozza üresen Egyszerre egy rekordot kezelhetünk

61 Olvasás Open állomány for Random Get utasítás

62 Get Általában a Form_Load-ban Do Until
Get #FileNumber, [RecordNumber], RecordName Get #2, 4, mudtPersonRecord Get #2, intRecordNumber, mudtPersonRecord Ha a RecordNumber hiányzik, a következőt olvassuk

63 Put Random file írására Nyitva kell lennie "For Random" Általában:
mnuFileSave, mnuFileClose vagy Form_QueryUnload Close követi

64 Put Put #FileNumber, [RecordNumber], RecordName
Put #2, 4, mudtPersonRecord Put #2, intRecordNumber, mudtPersonRecord Ha RecordNumber hiányzik, a következőt olvassuk

65 Mezőkhöz való hozzáférés
Get és Put „pont jelölés”, segítség a User Defined Type megnézése

66 Példa Get Put: Get #2, 1, mudtPersonRecord
txtLName.Text=mudtPersonRecord.strLName Put: mudtPersonRecord.strPhone=txtPhone.Text Put #2, 1, mudtPersonRecord

67 LOF Függvény Length of File: a Fájl mérete byte-ban
EOF helyett lehet használni Maxrekszám=LOF/rekméret LOF(FileNumber) LOF(3) intNumRecords=LOF(3)/Len(mudtPersonRecord)

68 Seek Függvény A fájlmutató értékét adja visza Seek(FileNumber)
intNextRecord=Seek(3)

69 Trim Függvény Kitörli az üres helyeket egy sztringből
Trim ==> mindkét végéről LTrim==> left RTrim ==> right Trim(String) LTrim(String) RTrim(String) txtLName.Text=RTrim(mudtPersonRecord.strLName)

70 Példa Sub GetRecord(lngRecNum as Long)
Get #1, lngRecNum, mudtPersonRecord With mudtPhoneRecord txtEmpNum.Text = .intEmpNum txtFName.Text = RTrim(.strFName) txtLName.Text = Rtrim(.strLName) txtPhone.Text = Rtrim(.strPhone) txtRate.Text = .curRate End With End Sub

71 Példa Sub PutRecord(lngRecNum as Long) With mudtPhoneRecord
.intEmpNum=Val(txtEmpNum.Text) .strFName = txtFName.Text .strLName = txtLName.Text .strPhone = txtPhone.Text .curRate = Val(txtRate.Text) End With Put #1, lngRecNum, mudtPersonRecord End Sub

72 Grafika

73 Grafika Mértékek és koordináta rendszer
Használjuk a RGB és QBColor függvényeket a színekhez Grafika létrehozása Load/change picture futási időben Egyszerű animáció létrehozása Timer control

74 The Graphics Environment
Scale=mértékegység rendszer twips, point, pixels, inches vagy centimeters (default: twips) Twip = 1/20 point; point = 1/72 inch Pixel: Picture element A koordináta rendszer origója 0,0 (x,y) a balfelső sarokban A konténereknek (pl. picture box) saját belső koordináta rendszerük van 0,0

75 Koordináta rendszer Olvasása/írása: ScaleLeft, ScaleTop, ScaleWidth, ScaleHeight Image: Stretch property Image-t hsználjunk ha lehet PictureBox helyett (gyorsabb) picturebox control image control picturebox tool image tool

76 Színek ForeColor, BackColor, FillColor
RGB függvény, konstansok (vbRed) A QBColor függvény átkonvertálja a régi színkonstansokat (0-15) a nekik megfelelő RGB-be: frmMain.BackColor = QBColor(1) ‘Blue RGB function: RGB(RedValue, GreenValue, BlueValue) Examples: lblWarning.BackColor = RGB(255, 0, 0) ‘Red txtName.ForeColor = RGB(255, 0, 255) ‘Magenta RGB color values for some standard colors: Visual basic Intrinsic Color constants: vbBlack, vbBlue, vbGreen, vbCyan, vbRed, vbMagenta, vbYellow, vbWhite

77 Grafikus metódusok Form, Picturebox, Printer objektumokon rajzolnakcts
Default: form Pl: Cls, Pset, Line, Circle Mások, mint a grafikus vezérklők Újra kell rajzolni a grafikát, ha eltűnik, majd megjelenik egy form When a form is resized or covered by another window and then redisplayed, any method-drawn graphics are not repainted—they disappear. To make method-drawn graphics persist when a form is hidden and then redisplayed, place the graphics-drawing methods in the Paint event for the form or picturebox. Of course, you can place the methods in a user event such as a command button’s Click event. The Cls method clears the specific object. Default object is a form Cls ‘clear the background of the form picPicture.Cls ‘clear a picture box The Pset method places a single point at the specifiec coordinates— (x,y) picPicture.PSet (5,25), vbRed picPicture.PSet (1000,1000) Default property for PSet is the ForeColor property when the property is omitted the coordinates may be variables—presumably, integer

78 …. Circle kerekített alakzatokra:
DrawWidth vastagság Line szakasz (B paraméterrel téglalap) Circle kerekített alakzatokra: circles, ovals, arcs, pie-shaped wedges PSet example (page 559): Line method can draw a box with the B parameter (B stands for “box”) Line (0, 0) - (500, 500), , B ‘Draw a box A box can be filled with a pattern, based on the FillStyle property Draw a circle: Circle(1000,1000),500 Form: [Object].Circle (X,Y), Radius [, Color [, StartAngle, EndAngle [, AspectRatio] ] ] Step method changes the coordinates from absolute to relative random dots painted on form in random colors

79 Rétegezés Az objektumok más-más rétegen vannak Fedik egymást a rétegek
Az alapértelmezett rétegre kerülnek az objektumok AutoRedraw , ClipControls tulajdonságokkal befolyásolhatjuk a rétegek viselkedését Set the AutoRedraw property to True to get persistent graphics, which are graphics that are automatically redrawn when the object is redisplayed or resized. This is equivalent to setting AutoRedraw to False and using the Paint event to redraw all graphics on a redisplayed object. AutoRedraw set to True consumes memory resources. The clipping region determines which portions of the screen will be painted. Here are some guidelines for graphics: 1. When AutoRedraw is set to False, place graphics methods in the Paint event of the form or container. 2. Setting the AutoRedraw to True always provides normal layering but will slow the performance due to large memory requirements. Set the stacking order of objects within a single layer by using the ZOrder method. graphics method label picture control Front: command buttons, check boxes, nongraphic controls Middle: Labels, graphics controls Back: graphic shapes (methods)

80 Még egy-két dolog Lehet képeket hozzáadni futási és tervezési időben is Elhelyezés: image, picturebox, form Picture property! A form Picture tulajdonsága a vezérlők mögött jelenik meg A LoadPicture függvény futási időben tölt be egy képet a vezérlőbe Suppose an image is already in a Picture control that is currently invisible: picLogo.Visible = True ‘make picture control visible Alternatively, you can load the picture at run time from another object on the form that is invisible: imgLogo.Picture = picLogo.Picture You can use the LoadPicture function to retrieve a file at run time—problem: the path to the picture must be known, and you cannot know the path on another person’s computer. picLogo.Picture = LoadPicture(“C:\VB\Logo.bmp”) To erase (empty) a picture control, either hide it or use LoadPicture to empty it: picLogo.Visible = False or picLogo.Picture = LoadPicture(“”) You can move a picture control by changing the valuse of the Left and Top properties. Also, you can use the Move method. Move method: [object].move Left [, Top [, Width [, Height]]] Line controls must be Moved because they do not have Left or Top properties.

81 Simple Amimation Animate an object by:
toggling between two pictures, moving a picture, moving a picture, or rotating through a series of pictures VB icon library graphics often have two graphics of same size but opposite states (pushed in and out, for example) Animate picking up the phone with two hidden images that are alternately loaded into an image control. Design time view of such a program is this: hidden images that are loaded into the image control Image control into which images are loaded

82 The Timer Control The Timer control triggers events at a programmer-specified time interval Timer control is invisible at run time—simply place it on a form Control triggers each time an interval elapses Set the Interval property (0 to 65,535) in milleseconds; disable by setting timer’s Enabled property to False

83 More Graphics Techniques
Use the Scale method to change the scale of your coordinate system [Object].Scale (x1, y1) - (x2, y2) picLogo.Scale (0, 0) - (100, 100) changes the scale to 0 through 100 PaintPicture method places a graphic file on a form, picturebox, or the printer PaintPicture picLogo.Picture, 100, 100 Example of the PaintPicture method in action. First, create a picture box populated with the icon you want to tile. Next, hide the picture box (.Visible = False). Third, write the code to execute PaintPicture for consistently varying coordinates:


Letölteni ppt "Objektum Orientált Programozás"

Hasonló előadás


Google Hirdetések