Thisdocumentiscopyright(C)StanfordComputerScienceandMartyStepp,licensedunderCreativeCommonsAttribution2.5License.Allrightsreserved.BasedonslidescreatedbyKeithSchwarz,MehranSahami,EricRoberts,StuartReges,andothers.
CS106A,Lecture14EventsandInstanceVariables
Reading:Art&ScienceofJava,Ch.10.1-10.4
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!}
12
Plan for Today•Announcements•Review:Animation•Null•Event-drivenprogramming(withDaisy!)•InstanceVariables•Whack-A-Mole
13
Events•event:Someexternalstimulusthatyourprogramcanrespondto.
•event-drivenprogramming:Acodingstyle(commoningraphicalprograms)whereyourcodeisexecutedinresponsetouserevents.
15
Events•Programlaunches•Mousemotion•Mouseclicking•Keyboardkeyspressed•Devicerotated•Devicemoved•GPSlocationchanged•andmore…
16
Events•Programlaunches•Mousemotion•Mouseclicking•Keyboardkeyspressed•Devicerotated•Devicemoved•GPSlocationchanged•andmore…
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
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
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!
37
Plan for Today•Announcements•Review:Animation•Null•Event-drivenprogramming(withDaisy!)•InstanceVariables•Whack-A-Mole
39
Whack-A-MoleLet’suseinstancevariablesandeventstomakeWhack-A-Mole!• Amoleshouldappeareverysecondatarandomlocation,andstoponcetheuserhasgottenatleast10points.
• Iftheuserclicksamole,removeitandincreasetheirscoreby1• ThereshouldbeaGLabel intheleftcornershowingtheirscore
40
Exception• Iftheuserclicksanareawithnomole,theprogramcrashes.
– AprogramcrashinJavaiscalledanexception.– Whenyougetanexception,Eclipseshowsrederrortext.– Theerrortextshowsthelinenumberwheretheerroroccurred.– Whydidthiserrorhappen?– Howcanweavoidthis?