Top Banner
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
41

CS 106A, Lecture 14 Events and Instance Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

May 10, 2018

Download

Documents

phungkien
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: CS 106A, Lecture 14 Events and Instance Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

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 Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

2

GraphicsPrograms

Animation

HW4:Breakout

Youarehere

Page 3: CS 106A, Lecture 14 Events and Instance Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

3

Learning Goals• LearntorespondtomouseeventsinGraphicsPrograms• Learntouseinstancevariablestostoreinformationoutsideofmethods

Page 4: CS 106A, Lecture 14 Events and Instance Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

4

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

Page 5: CS 106A, Lecture 14 Events and Instance Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

5

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

Page 6: CS 106A, Lecture 14 Events and Instance Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

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 Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

7

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

Page 8: CS 106A, Lecture 14 Events and Instance Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

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 Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

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 Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

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 Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

11

NullCallingmethodsonanobjectthatisnull willcrashyourprogram!(throwsaNullPointerException)

Page 12: CS 106A, Lecture 14 Events and Instance Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

12

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

Page 13: CS 106A, Lecture 14 Events and Instance Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

13

Events•event:Someexternalstimulusthatyourprogramcanrespondto.

•event-drivenprogramming:Acodingstyle(commoningraphicalprograms)whereyourcodeisexecutedinresponsetouserevents.

Page 14: CS 106A, Lecture 14 Events and Instance Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

14

Events•Programlaunches

Page 15: CS 106A, Lecture 14 Events and Instance Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

15

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

Page 16: CS 106A, Lecture 14 Events and Instance Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

16

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

Page 17: CS 106A, Lecture 14 Events and Instance Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

17

Events

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

}

Page 18: CS 106A, Lecture 14 Events and Instance Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

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 Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

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 Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

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 Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

21

MouseEvent Objects

•AMouseEvent containsinformationabouttheeventthatjustoccurred:

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

Page 22: CS 106A, Lecture 14 Events and Instance Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

22

Example: ClickForDaisies

Page 23: CS 106A, Lecture 14 Events and Instance Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

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 Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

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 Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

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 Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

26

Example: Doodler

Page 27: CS 106A, Lecture 14 Events and Instance Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

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 Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

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 Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

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 Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

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 Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

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 Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

32

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

Page 33: CS 106A, Lecture 14 Events and Instance Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

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 Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

34

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

Page 35: CS 106A, Lecture 14 Events and Instance Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

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 Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

36

Example: MouseTracker

Page 37: CS 106A, Lecture 14 Events and Instance Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

37

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

Page 38: CS 106A, Lecture 14 Events and Instance Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

38

Putting it all together

Page 39: CS 106A, Lecture 14 Events and Instance Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

39

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

• Iftheuserclicksamole,removeitandincreasetheirscoreby1• ThereshouldbeaGLabel intheleftcornershowingtheirscore

Page 40: CS 106A, Lecture 14 Events and Instance Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

40

Exception• Iftheuserclicksanareawithnomole,theprogramcrashes.

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

Page 41: CS 106A, Lecture 14 Events and Instance Variablesweb.stanford.edu/class/archive/cs/cs106a/cs106a.1178/lectures/...5 Plan for Today •Announcements •Review: Animation •Null •Event-driven

41

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

NextTime:MoreEvents+Memory