cs 106a, lecture 14 events and instance variables · 2017. 7. 19. · 35 instance variables private...

41
This document is copyright (C) Stanford Computer Science and Marty Stepp, licensed under Creative Commons Attribution 2.5 License. All rights reserved. Based on slides created by Keith Schwarz, Mehran Sahami, Eric Roberts, Stuart Reges, and others. CS 106A, Lecture 14 Events and Instance Variables Reading: Art & Science of Java, Ch. 10.1-10.4

Upload: others

Post on 05-Sep-2020

0 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.

CS106A,Lecture14EventsandInstanceVariables

Reading:Art&ScienceofJava,Ch.10.1-10.4

Page 2: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

2

GraphicsPrograms

Animation

HW4:Breakout

Youarehere

Page 3: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

3

Learning Goals• LearntorespondtomouseeventsinGraphicsPrograms• Learntouseinstancevariablestostoreinformationoutsideofmethods

Page 4: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

4

Plan for Today•Announcements•Review:Animation•Null•Event-drivenprogramming(withDaisy!)•InstanceVariables•Whack-A-Mole

Page 5: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

5

Plan for Today•Announcements•Review:Animation•Null•Event-drivenprogramming(withDaisy!)•InstanceVariables•Whack-A-Mole

Page 6: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

6

Animation• AGraphicsprogramcanbemadetoanimatewithaloopsuchas:

public void run() {...while (test) {

update the position of shapes;pause(milliseconds);

}

}

• Thebestnumberofmstopausedependsontheprogram.– mostvideogames~=50frames/sec=25mspause

Page 7: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

7

Plan for Today•Announcements•Review:Animation•Null•Event-drivenprogramming(withDaisy!)•InstanceVariables•Whack-A-Mole

Page 8: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

8

NullNullisaspecialvariablevaluethatobjects canhavethatmeans“nothing”.Primitives cannotbenull.

Ifamethodreturnsanobject,itcanreturnnull tosignify“nothing”.(justsayreturn null;)

// may be a GObject, or null if nothing at (x, y)GObject maybeAnObject = getElementAt(x, y);

Objectshavethevaluenull beforebeinginitialized.

Scanner myScanner; // initially null

Page 9: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

9

NullYoucancheckifsomethingisnullusing==and!=.

// may be a GObject, or null if nothing at (x, y)GObject maybeAnObject = getElementAt(x, y);if (maybeAnObject != null) {

// do something with maybeAnObject} else {

// null – nothing at that location}

Page 10: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

10

NullCallingmethodsonanobjectthatisnull willcrashyourprogram!

// may be a GObject, or null if nothing at (x, y)GObject maybeAnObject = getElementAt(x, y);if (maybeAnObject != null) {

int x = maybeAnObject.getX(); // OK} else {

int x = maybeAnObject.getX(); // CRASH!}

Page 11: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

11

NullCallingmethodsonanobjectthatisnull willcrashyourprogram!(throwsaNullPointerException)

Page 12: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

12

Plan for Today•Announcements•Review:Animation•Null•Event-drivenprogramming(withDaisy!)•InstanceVariables•Whack-A-Mole

Page 13: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

13

Events•event:Someexternalstimulusthatyourprogramcanrespondto.

•event-drivenprogramming:Acodingstyle(commoningraphicalprograms)whereyourcodeisexecutedinresponsetouserevents.

Page 14: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

14

Events•Programlaunches

Page 15: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

15

Events•Programlaunches•Mousemotion•Mouseclicking•Keyboardkeyspressed•Devicerotated•Devicemoved•GPSlocationchanged•andmore…

Page 16: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

16

Events•Programlaunches•Mousemotion•Mouseclicking•Keyboardkeyspressed•Devicerotated•Devicemoved•GPSlocationchanged•andmore…

Page 17: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

17

Events

public void run() {// Java runs this when program launches

}

Page 18: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

18

Events

public void run() {// Java runs this when program launches

}

public void mouseClicked(MouseEvent event) {// Java runs this when mouse is clicked

}

Page 19: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

19

Events

public void run() {// Java runs this when program launches

}

public void mouseClicked(MouseEvent event) {// Java runs this when mouse is clicked

}

public void mouseMoved(MouseEvent event) {// Java runs this when mouse is moved

}

Page 20: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

20

Example: ClickForDaisyimport acm.program.*;import acm.graphics.*;import java.awt.*;import java.awt.event.*; // NEW

public class ClickForDaisy extends GraphicsProgram {

// Add a Daisy image at 50, 50 on mouse clickpublic void mouseClicked(MouseEvent event) {

GImage daisy = new GImage("res/daisy.png", 50, 50);add(daisy);

}}

Page 21: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

21

MouseEvent Objects

•AMouseEvent containsinformationabouttheeventthatjustoccurred:

Method Descriptione.getX() thex-coordinateofmousecursorinthewindowe.getY() they-coordinateofmousecursorinthewindow

Page 22: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

22

Example: ClickForDaisies

Page 23: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

23

Example: ClickForDaisiespublic class ClickForDaisies extends GraphicsProgram {

// Add a Daisy image where the user clickspublic void mouseClicked(MouseEvent event) {// Get information about the eventdouble mouseX = event.getX();double mouseY = event.getY();

// Add Daisy at the mouse locationGImage daisy = new GImage("res/daisy.png", mouseX, mouseY);add(daisy);

}}

Page 24: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

24

Example: ClickForDaisiespublic class ClickForDaisies extends GraphicsProgram {

// Add a Daisy image where the user clickspublic void mouseClicked(MouseEvent event) {// Get information about the eventdouble mouseX = event.getX();double mouseY = event.getY();

// Add Daisy at the mouse locationGImage daisy = new GImage("res/daisy.png", mouseX, mouseY);add(daisy);

}}

Page 25: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

25

Types of Mouse Events• Therearemanydifferenttypesofmouseevents.

– Eachtakestheform:public void eventMethodName(MouseEvent event) { ...

Method DescriptionmouseMoved mousecursormovesmouseDragged mousecursormoveswhilebuttonishelddownmousePressed mousebuttonispresseddownmouseReleased mousebuttonisliftedupmouseClicked mousebuttonispressedandthenreleasedmouseEntered mousecursorentersyourprogram'swindowmouseExited mousecursorleavesyourprogram'swindow

Page 26: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

26

Example: Doodler

Page 27: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

27

Doodlerprivate static final int SIZE = 10;...

public void mouseDragged(MouseEvent event) {double mouseX = event.getX();double mouseY = event.getY();double rectX = mouseX – SIZE / 2.0;double rectY = mouseY – SIZE / 2.0;GRect rect = new GRect(rectX, rectY, SIZE, SIZE);rect.setFilled(true);add(rect);

}

Page 28: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

28

Doodlerpublic void mouseDragged(MouseEvent event) {

double mouseX = event.getX();double mouseY = event.getY();double rectX = mouseX – SIZE / 2.0;double rectY = mouseY – SIZE / 2.0;GRect rect = new GRect(rectX, rectY, SIZE, SIZE);rect.setFilled(true);add(rect);

}

Page 29: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

29

Doodlerpublic void mouseDragged(MouseEvent event) {

double mouseX = event.getX();double mouseY = event.getY();double rectX = mouseX – SIZE / 2.0;double rectY = mouseY – SIZE / 2.0;GRect rect = new GRect(rectX, rectY, SIZE, SIZE);rect.setFilled(true);add(rect);

}

Page 30: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

30

Doodlerpublic void mouseDragged(MouseEvent event) {

double mouseX = event.getX();double mouseY = event.getY();double rectX = mouseX – SIZE / 2.0;double rectY = mouseY – SIZE / 2.0;GRect rect = new GRect(rectX, rectY, SIZE, SIZE);rect.setFilled(true);add(rect);

}

Page 31: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

31

Doodlerpublic void mouseDragged(MouseEvent event) {

double mouseX = event.getX();double mouseY = event.getY();double rectX = mouseX – SIZE / 2.0;double rectY = mouseY – SIZE / 2.0;GRect rect = new GRect(rectX, rectY, SIZE, SIZE);rect.setFilled(true);add(rect);

}

Page 32: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

32

Recap: Events1)Userperformssomeaction,likemoving/clickingthemouse.2)Thiscausesaneventtooccur.3)Javaexecutesaparticularmethodtohandlethatevent.4)Themethod'scodeupdatesthescreenappearanceinsomeway.

Page 33: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

33

Revisiting Doodlerpublic void mouseDragged(MouseEvent event) {

double mouseX = event.getX();double mouseY = event.getY();double rectX = mouseX – SIZE / 2.0;double rectY = mouseY – SIZE / 2.0;GRect rect = new GRect(rectX, rectY, SIZE, SIZE);rect.setFilled(true);add(rect);

}

Whatifwewantedthesame GRect totrackthemouse,insteadofmakinganewoneeachtime?

Page 34: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

34

Plan for Today•Announcements•Review:Animation•Null•Event-drivenprogramming(withDaisy!)•InstanceVariables•Whack-A-Mole

Page 35: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

35

Instance Variablesprivate type name; // declared outside of any method

• Instancevariable:Avariablethatlivesoutsideofanymethod.– Thescope ofaninstancevariableisthroughoutanentirefile(class).

– Usefulfordatathatmustpersistthroughouttheprogram,orthatcannotbestoredaslocalvariablesorparameters(eventhandlers).

– Itisbadstyletooveruseinstancevariables

DONOTUSEINSTANCEVARIABLESONHANGMAN!

Page 36: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

36

Example: MouseTracker

Page 37: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

37

Plan for Today•Announcements•Review:Animation•Null•Event-drivenprogramming(withDaisy!)•InstanceVariables•Whack-A-Mole

Page 38: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

38

Putting it all together

Page 39: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

39

Whack-A-MoleLet’suseinstancevariablesandeventstomakeWhack-A-Mole!• Amoleshouldappeareverysecondatarandomlocation,andstoponcetheuserhasgottenatleast10points.

• Iftheuserclicksamole,removeitandincreasetheirscoreby1• ThereshouldbeaGLabel intheleftcornershowingtheirscore

Page 40: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

40

Exception• Iftheuserclicksanareawithnomole,theprogramcrashes.

– AprogramcrashinJavaiscalledanexception.– Whenyougetanexception,Eclipseshowsrederrortext.– Theerrortextshowsthelinenumberwheretheerroroccurred.– Whydidthiserrorhappen?– Howcanweavoidthis?

Page 41: CS 106A, Lecture 14 Events and Instance Variables · 2017. 7. 19. · 35 Instance Variables private type name; // declared outside of any method •Instance variable: A variable that

41

Recap•Announcements•Review:Animation•Null•Event-drivenprogramming(withDaisy!)•InstanceVariables•Whack-A-Mole

NextTime:MoreEvents+Memory