CS 106A, Lecture 14 Events and Instance Variables

Slides:



Advertisements
Similar presentations
JQuery MessageBoard. Lets use jQuery and AJAX in combination with a database to update and retrieve information without refreshing the page. Here we will.
Advertisements

Introduction to Macromedia Director 8.5 – Lingo
Understanding an Apps Architecture ASFA Computer Science: Principles Fall 2013.
 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
Mouse Listeners We continue our examination of GUIs by looking at how to interact with the mouse –Just as Java creates Events when the user interacts with.
IAT 800 Lab 1: Loops, Animation, and Simple User Interaction.
Event Handling Events and Listeners Timers and Animation.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Lecture 18 Review the difference between abstract classes and interfaces The Cloneable interface Shallow and deep copies The ActionListener interface,
PROCESSING Animation. Objectives Be able to create Processing animations Be able to create interactive Processing programs.
GAME:IT Junior Bouncing Ball Objectives: Create Sprites Create Sounds Create Objects Create Room Program simple game.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Introduction to Scratch!
Chapter 11 Java AWT Part I: Mouse Events (Optional) Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin,
1 Event Driven Programs Rick Mercer. 2 So what happens next?  You can layout a real pretty GUI  You can click on buttons, enter text into a text field,
Keyboard and Events. What about the keyboard? Keyboard inputs can be used in many ways---not just for text The boolean variable keyPressed is true if.
KeyListener and Keyboard Events Another type of listener listens for keyboard entry – the KeyListener which generates KeyEvents –to implement KeyListener,
Java GUI’s are event driven, meaning they generate events when the user interacts with the program. Typical events are moving the mouse, clicking a mouse.
(c) University of Washington07b-1 CSC 143 Java Events, Event Handlers, and Threads Reading: Ch. 17.
7/3/00SEM107- © Kamin & ReddyClass 11 - Events - 1 Class 11 - Events r A couple of odds & ends m Component sizes  switch statement r Event types r Catching.
Lesson 34: Layering Images with Java GUI. The FlowLayout RECAP.
12/5/00SEM107, Kamin & ReddyReview - 34 Events Event types Catching different event types Getting information from components and events Distinguishing.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 21.1 Test-Driving the Painter Application.
UID – Event Handling and Listeners Boriana Koleva
CS-1020 Dr. Mark L. Hornick 1 Event-Driven Programming.
CIS 3.5 Lecture 2.2 More programming with "Processing"
Mouse Listeners Moving the mouse will also generate events like the Timer –To have your program respond, you must implement either or both of MouseListener.
SCRIPT PROGRAMMING WITH FLASH Introductory Level 1.
What Is an Event? Events – Objects that describe what happened Event sources – The generator of an event Event handlers – A method that receives an event.
Creating a Simple Game in Scratch Barb Ericson Georgia Tech May 2009.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
CS 106A, Lecture 27 Final Exam Review 1
CS 134 Alternate Inputs.
Create a Halloween Computer Game in Scratch
Scratch for Interactivity
PYGAME.
“Form Ever Follows Function” Louis Henri Sullivan
Computer Science 209 Graphics and GUIs.
Review.
Intro CS – Keyboard and mouse input
Testing and Debugging.
Interfaces.
Understanding an App’s Architecture
Creating and Modifying Text part 2
CS106A, Stanford University
Introduction to Events
Programming in Java Event Handling
Windows Desktop Applications
reading: Art & Science of Java,
CS 106A, Lecture 15 Events and Memory
PC02 Term 1 Project Basic Messenger. PC02 Term 1 Project Basic Messenger.
CS 106A, Lecture 24 Interactors and NameSurfer
Event Driven Programming
Computation as an Expressive Medium
Exceptions 10-Nov-18.
reading: Art & Science of Java, Ch. 9
CS 106A, Lecture 12 More Graphics
CS 106A, Lecture 22 More Classes
Introduction to Computing Using Java
Web Design & Development Lecture 12
Graphics.
Unit 11 – PowerPoint Interaction
More programming with "Processing"
Events, Event Handlers, and Threads
Tonga Institute of Higher Education
LCC 6310 Computation as an Expressive Medium
Exceptions 10-May-19.
Creating a Simple Game in Scratch
3.2 Working with Data Scope of variables 29/07/2019.
Presentation transcript:

CS 106A, Lecture 14 Events and Instance Variables Reading: Art & Science of Java, Ch. 10.1-10.4

HW4: Breakout The River of Java Memory Events You are here Animation Graphics Programs

Learning Goals Learn to respond to mouse events in GraphicsPrograms Learn to use instance variables to store information outside of methods

Plan for Today Announcements Review: Animation Null Event-driven programming (with Daisy!) Instance Variables Whack-A-Mole

Plan for Today Announcements Review: Animation Null Event-driven programming (with Daisy!) Instance Variables Whack-A-Mole

Animation A Graphics program can be made to animate with a loop such as: public void run() { ... while (test) { update the position of shapes; pause(milliseconds); } The best number of ms to pause depends on the program. most video games ~= 50 frames/sec = 25ms pause

Plan for Today Announcements Review: Animation Null Event-driven programming (with Daisy!) Instance Variables Whack-A-Mole

Null Null is a special variable value that objects can have that means “nothing”. Primitives cannot be null. If a method returns an object, it can return null to signify “nothing”. (just say return null;) // may be a GObject, or null if nothing at (x, y) GObject maybeAnObject = getElementAt(x, y); Objects have the value null before being initialized. Scanner myScanner; // initially null Different from the empty string

Null You can check if something is null using == 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 } This is how we can finish dribbleCastle!

Null Calling methods on an object that is null will crash your program! // 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! } Think about null like an “invalid mailing address” – if you try to send messages to it, your messages bounce because the address is invalid

Null Calling methods on an object that is null will crash your program! (throws a NullPointerException)

Plan for Today Announcements Review: Animation Null Event-driven programming (with Daisy!) Instance Variables Whack-A-Mole

Events event: Some external stimulus that your program can respond to. event-driven programming: A coding style (common in graphical programs) where your code is executed in response to user events. 11:40AM

Events Program launches When that event happens, Java looks for a method in your program called public void run and executes the code there. Today, we’re going to learn about other types of events besides your program launching.  There are lots of them! And it turns out you can also have Java run certain code when those things happen, too.

Events Program launches Mouse motion Mouse clicking Keyboard keys pressed Device rotated Device moved GPS location changed and more… These are events triggered by the user – like mouse clicks, or mouse drags.  On mobile devices, there are even more. We are now just demoting run to be “another event” that is triggered by the user

Events Program launches Mouse motion Mouse clicking Keyboard keys pressed Device rotated Device moved GPS location changed and more… We’re just going to focus on the mouse today. These can happen in any order – mouse events even after run finishes!

Events public void run() { // Java runs this when program launches } The rule in Java though is that the code for each event needs to go in its own method.  That way Java knows what to execute for each event.  They also have to be named exactly how Java wants, so it knows where to look. So we have a method for the code that should be run when the program launches (public void run()). And we also will have a method for the code that should run when the user clicks the mouse, and a method that should run when the user drags the mouse, etc.

Events public void run() { // Java runs this when program launches } public void mouseClicked(MouseEvent event) { // Java runs this when mouse is clicked these new methods also have to be specifically named.

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 these new methods also have to be specifically named. Just like run, these methods are called by Java, not by our code!

Example: ClickForDaisy import 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 click public void mouseClicked(MouseEvent event) { GImage daisy = new GImage("res/daisy.png", 50, 50); add(daisy); } No run method! Make sure prototype is exact! Show working program. Adds daisies always at the same location This is nice, but not very exciting if we can only add a Daisy image at one location. It would be cool if we could get information about the event that just happened. Luckily, we can! You’ll notice something different here from run() – it takes a parameter!  This is because when an event happens, Java will call our method and pass us some information about the event in this parameter.

MouseEvent Objects A MouseEvent contains information about the event that just occurred: Method Description e.getX() the x-coordinate of mouse cursor in the window e.getY() the y-coordinate of mouse cursor in the window Let’s try to use this parameter to make our ClickForDaisy program better – let’s add Daisy wherever the user clicks the mouse!

Example: ClickForDaisies How would we do this?

Example: ClickForDaisies public class ClickForDaisies extends GraphicsProgram { // Add a Daisy image where the user clicks public void mouseClicked(MouseEvent event) { // Get information about the event double mouseX = event.getX(); double mouseY = event.getY(); // Add Daisy at the mouse location GImage daisy = new GImage("res/daisy.png", mouseX, mouseY); add(daisy); }

Example: ClickForDaisies public class ClickForDaisies extends GraphicsProgram { // Add a Daisy image where the user clicks public void mouseClicked(MouseEvent event) { // Get information about the event double mouseX = event.getX(); double mouseY = event.getY(); // Add Daisy at the mouse location GImage daisy = new GImage("res/daisy.png", mouseX, mouseY); add(daisy); } One problem – where does Daisy show up? Show working program.

Types of Mouse Events There are many different types of mouse events. Each takes the form: public void eventMethodName(MouseEvent event) { ... Method Description mouseMoved mouse cursor moves mouseDragged mouse cursor moves while button is held down mousePressed mouse button is pressed down mouseReleased mouse button is lifted up mouseClicked mouse button is pressed and then released mouseEntered mouse cursor enters your program's window mouseExited mouse cursor leaves your program's window We’ve just talked about mouseClicked – there are many other types of mouse events you can react to! You can detect multiple events, but multiple mouse events can’t happen simultaneously HOWEVER – run can execute simultaneously with mouse events mouse dragged called many times while mouse is dragged – we can take advantage of this!

Example: Doodler Let’s look at an example with mouseDragged – let’s write a program that lets the user drag the mouse and drag

Doodler private 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); } Let’s step through

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

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

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

Doodler 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); } Show working program – question: why does it slow down when I move faster?

Recap: Events 1) User performs some action, like moving / clicking the mouse. 2) This causes an event to occur. 3) Java executes a particular method to handle that event. 4) The method's code updates the screen appearance in some way. This whole concept is called event-driven programming, and is a common way to write Graphics programs, since users can interact with them and you want to do things when they interact with them. This is different from how we have programmed so far, because unlike with run() we don’t know when our code will execute! It could be in any order.

Revisiting Doodler 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); } No way to do this! We can’t pass parameters since we don’t call mouse event methods No way for information to live between mouse dragged calls – no variables live then! No way to access information about previous drag What if we wanted the same GRect to track the mouse, instead of making a new one each time?

Plan for Today Announcements Review: Animation Null Event-driven programming (with Daisy!) Instance Variables Whack-A-Mole

DO NOT USE INSTANCE VARIABLES ON HANGMAN! private type name; // declared outside of any method Instance variable: A variable that lives outside of any method. The scope of an instance variable is throughout an entire file (class). Useful for data that must persist throughout the program, or that cannot be stored as local variables or parameters (event handlers). It is bad style to overuse instance variables DO NOT USE INSTANCE VARIABLES ON HANGMAN! Because they have a large scope, it is considered bad style to use too many instance variables, or to make something an instance variable that could instead be a local variable, parameter, return, etc.

Example: MouseTracker Write mouseTracker with creating Grect in run, moving grect in mouse moved. Then, show that we can’t access Grect in mouse moved. We need a field! Show code, add field.

Plan for Today Announcements Review: Animation Null Event-driven programming (with Daisy!) Instance Variables Whack-A-Mole

Putting it all together

Whack-A-Mole Let’s use instance variables and events to make Whack-A-Mole! A mole should appear every second at a random location, and stop once the user has gotten at least 10 points. If the user clicks a mole, remove it and increase their score by 1 There should be a GLabel in the left corner showing their score Show demo first Think-pair-share: what events might we want to respond to, and what instance variables might we need? Run: adding moles MouseClicked – remove moles, increment score Ivars: label and score

Exception If the user clicks an area with no mole, the program crashes. A program crash in Java is called an exception. When you get an exception, Eclipse shows red error text. The error text shows the line number where the error occurred. Why did this error happen? How can we avoid this? How to interpret crash messages

Recap Announcements Review: Animation Null Event-driven programming (with Daisy!) Instance Variables Whack-A-Mole Next Time: More Events + Memory