Page 1
Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
CS106A,Lecture14EventsandInstanceVariables
Reading:Art&ScienceofJava,Ch.10.1-10.4
Page 2
2
GraphicsPrograms
Animation
HW4:Breakout
Youarehere
Page 3
3
Learning Goals• LearntorespondtomouseeventsinGraphicsPrograms• Learntouseinstancevariablestostoreinformationoutsideofmethods
Page 4
4
Plan for Today•Announcements•Review:Animation•Null•Event-drivenprogramming(withDaisy!)•InstanceVariables•Whack-A-Mole
Page 5
5
Plan for Today•Announcements•Review:Animation•Null•Event-drivenprogramming(withDaisy!)•InstanceVariables•Whack-A-Mole
Page 6
6
Animation• AGraphicsprogramcanbemadetoanimatewithaloopsuchas:
public void run() {...while (test) {
update the position of shapes;pause(milliseconds);
}
}
• Thebestnumberofmstopausedependsontheprogram.– mostvideogames~=50frames/sec=25mspause
Page 7
7
Plan for Today•Announcements•Review:Animation•Null•Event-drivenprogramming(withDaisy!)•InstanceVariables•Whack-A-Mole
Page 8
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
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
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
11
NullCallingmethodsonanobjectthatisnull willcrashyourprogram!(throwsaNullPointerException)
Page 12
12
Plan for Today•Announcements•Review:Animation•Null•Event-drivenprogramming(withDaisy!)•InstanceVariables•Whack-A-Mole
Page 13
13
Events•event:Someexternalstimulusthatyourprogramcanrespondto.
•event-drivenprogramming:Acodingstyle(commoningraphicalprograms)whereyourcodeisexecutedinresponsetouserevents.
Page 14
14
Events•Programlaunches
Page 15
15
Events•Programlaunches•Mousemotion•Mouseclicking•Keyboardkeyspressed•Devicerotated•Devicemoved•GPSlocationchanged•andmore…
Page 16
16
Events•Programlaunches•Mousemotion•Mouseclicking•Keyboardkeyspressed•Devicerotated•Devicemoved•GPSlocationchanged•andmore…
Page 17
17
Events
public void run() {// Java runs this when program launches
}
Page 18
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
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
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
21
MouseEvent Objects
•AMouseEvent containsinformationabouttheeventthatjustoccurred:
Method Descriptione.getX() thex-coordinateofmousecursorinthewindowe.getY() they-coordinateofmousecursorinthewindow
Page 22
22
Example: ClickForDaisies
Page 23
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
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
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
26
Example: Doodler
Page 27
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
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
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
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
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
32
Recap: Events1)Userperformssomeaction,likemoving/clickingthemouse.2)Thiscausesaneventtooccur.3)Javaexecutesaparticularmethodtohandlethatevent.4)Themethod'scodeupdatesthescreenappearanceinsomeway.
Page 33
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
34
Plan for Today•Announcements•Review:Animation•Null•Event-drivenprogramming(withDaisy!)•InstanceVariables•Whack-A-Mole
Page 35
35
Instance Variablesprivate type name; // declared outside of any method
• Instancevariable:Avariablethatlivesoutsideofanymethod.– Thescope ofaninstancevariableisthroughoutanentirefile(class).
– Usefulfordatathatmustpersistthroughouttheprogram,orthatcannotbestoredaslocalvariablesorparameters(eventhandlers).
– Itisbadstyletooveruseinstancevariables
DONOTUSEINSTANCEVARIABLESONHANGMAN!
Page 36
36
Example: MouseTracker
Page 37
37
Plan for Today•Announcements•Review:Animation•Null•Event-drivenprogramming(withDaisy!)•InstanceVariables•Whack-A-Mole
Page 38
38
Putting it all together
Page 39
39
Whack-A-MoleLet’suseinstancevariablesandeventstomakeWhack-A-Mole!• Amoleshouldappeareverysecondatarandomlocation,andstoponcetheuserhasgottenatleast10points.
• Iftheuserclicksamole,removeitandincreasetheirscoreby1• ThereshouldbeaGLabel intheleftcornershowingtheirscore
Page 40
40
Exception• Iftheuserclicksanareawithnomole,theprogramcrashes.
– AprogramcrashinJavaiscalledanexception.– Whenyougetanexception,Eclipseshowsrederrortext.– Theerrortextshowsthelinenumberwheretheerroroccurred.– Whydidthiserrorhappen?– Howcanweavoidthis?
Page 41
41
Recap•Announcements•Review:Animation•Null•Event-drivenprogramming(withDaisy!)•InstanceVariables•Whack-A-Mole
NextTime:MoreEvents+Memory