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

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

Embed Size (px)

Citation preview

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

CS106A,Lecture14EventsandInstanceVariables

Reading:Art&ScienceofJava,Ch.10.1-10.4

2

GraphicsPrograms

Animation

HW4:Breakout

Youarehere

3

Learning Goals• LearntorespondtomouseeventsinGraphicsPrograms• Learntouseinstancevariablestostoreinformationoutsideofmethods

4

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

5

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

6

Animation• AGraphicsprogramcanbemadetoanimatewithaloopsuchas:

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

update the position of shapes;pause(milliseconds);

}

}

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

7

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

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

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}

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!}

11

NullCallingmethodsonanobjectthatisnull willcrashyourprogram!(throwsaNullPointerException)

12

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

13

Events•event:Someexternalstimulusthatyourprogramcanrespondto.

•event-drivenprogramming:Acodingstyle(commoningraphicalprograms)whereyourcodeisexecutedinresponsetouserevents.

14

Events•Programlaunches

15

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

16

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

17

Events

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

}

18

Events

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

}

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

}

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

}

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);

}}

21

MouseEvent Objects

•AMouseEvent containsinformationabouttheeventthatjustoccurred:

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

22

Example: ClickForDaisies

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);

}}

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);

}}

25

Types of Mouse Events• Therearemanydifferenttypesofmouseevents.

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

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

26

Example: Doodler

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);

}

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);

}

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);

}

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);

}

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);

}

32

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

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?

34

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

35

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

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

– Usefulfordatathatmustpersistthroughouttheprogram,orthatcannotbestoredaslocalvariablesorparameters(eventhandlers).

– Itisbadstyletooveruseinstancevariables

DONOTUSEINSTANCEVARIABLESONHANGMAN!

36

Example: MouseTracker

37

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

38

Putting it all together

39

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

• Iftheuserclicksamole,removeitandincreasetheirscoreby1• ThereshouldbeaGLabel intheleftcornershowingtheirscore

40

Exception• Iftheuserclicksanareawithnomole,theprogramcrashes.

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

41

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

NextTime:MoreEvents+Memory