Chapter 7: Pinball Game Construction Kit. Vectors Example of a “collection class” Must “import java.util.Vector” More flexible than arrays: will grow.

Slides:



Advertisements
Similar presentations
Made with love, by Zachary Langley Applets The Graphics Presentation.
Advertisements

 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.
Written by: Dr. JJ Shepherd
Inner Classes in Java CMSC 432 Shon Vick. 2 Conceptual Structure package p 1 class A 1 class A 2... class A n... package n class A 1 class A 2... class.
1 Inheritance. 2 One class inherits from another if it describes a specialized subset of objects Terminology: inheritschild class subclass –the class.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
Graphics Programming with Inheritance Template pattern (Chap 6, se SceneEditor)
GUI. Swing Class Hierarchy Swing Components Swing Conatiners  JFrame – top-level window to store components.
Lecture 18 Review the difference between abstract classes and interfaces The Cloneable interface Shallow and deep copies The ActionListener interface,
OOP Week 3 1 Object Oriented Programming in Java Monday, Week 3 Interface PinBallTarget OOP Concepts Last Week’s Assignment Arrays Collection Class --
GUI Event Handling Nithya Raman. What is an Event? GUI components communicate with the rest of the applications through events. The source of an event.
Abstract Classes and Interfaces
Copyright © 2003 ProsoftTraining. All rights reserved. Sun Certified Java Programmer Exam Preparation Guide.
OOP Languages: Java vs C++
Mouse Events. Handling Mouse Events Java provides two listener interfaces to handle mouse events: MouseListener;  MouseListener;  MouseMotionListener.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Session 12 Introduction to PinBallGame (Chaper 7).
Chapter 15 Multithreading F Threads Concept  Creating Threads by Extending the Thread class  Creating Threads by Implementing the Runnable Interface.
More Event Handling Adapters Anonymous Listeners Pop menus Validating User Input.
CS 11 java track: lecture 4 This week: arrays interfaces listener classes inner classes GUI callbacks.
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.
Session 11 Border Layout, using Panels, Introduction to PinBallGame.
Session 15 Chapter 8: Understanding Inheritance. Lab Exercise Solution Recall that we needed to know if a mousePress occurred on a target. We tried to.
CSE 501N Fall ‘09 20: Event Handling and Inner Classes 17 November 2009 Nick Leidenfrost.
Java Threads. What is a Thread? A thread can be loosely defined as a separate stream of execution that takes place simultaneously with and independently.
SD2071 Games Programming Abstraction, inheritance and interfaces Exceptions Two dimensional arrays Java collections framework Files Aaron Kans.
Previous programs used a JLabel for OUTPUT. Another Swing component that can be used for both user input and output is the JTextfield. Suppose we want.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Chapter 5: Ball Worlds Features 2 classes, constant data fields, constructors, extension through inheritance, graphics.
Graphics in Java CS 21b. The paint() Method Method in a visual component that specifies what that component looks like Particularly important for applets,
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
Session 16 Pinball Game Construction Kit:. Pinball Version 1 Replaced the fire button with a mouse event. Multiple balls can be in the air at once. –Uses.
Multithreading in Java Sameer Singh Chauhan Lecturer, I. T. Dept., SVIT, Vasad.
Session 19 Chapter 10 – Mechanisms for Software Reuse.
Session 18 Chapter 8: Understanding Inheritance. Recall Exercise 2 From Tuesday It’s very annoying to move a target from the pallet and drop it in the.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
Session 13 Pinball Game Construction Kit (Version 3):
Inheritance and Access Control CS 162 (Summer 2009)
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
Session 22 Chapter 11: Implications of Inheritance.
Session 25 Test 2 Review. Test 2 Details Tuesday, November 22 in class –(Anybody planning on taking it on Friday?) Closed book Closed notes, except for.
Interfaces Chapter 9. 9 Creating Interfaces An interface is a contract. Every class that implements the interface must provide the interface’s defined.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Session 18 Lab 9 Re-cap, Chapter 12: Polymorphism & Using Sound in Java Applications.
Lecture 7 February 24, Javadoc version and author Tags These go in the comments before named classes. –Put your SS# on a separate line from the.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
1 Event Handling – Lecture 4 Prepared by: Ahmad Ramin Rahimee Assistant Professor ICTI.
Laboratory Study November, Demonstrates Life Cycle of an Applet + Mouse Events + Scrolling.
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.
Quick topix 11/7/13 CSE 1102 Fall previous statement Execute rest of program Is true? yes no This flowchart illustrates the logic of a _________.
UQC117S2 Graphics Programming Lecture 2 Event Handling Program as a sequence of instructions Event -driven program Need to detect the event and carry out.
Session 7 More Implications of Inheritance & Chapter 5: Ball World Example.
Quick topix 11/7/13 CSE 1102 Fall previous statement Execute rest of program Is true? yes no This flowchart illustrates the logic of a _________.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
1 Block1-Unit 3 Using Inheritance Budd Tayseer AL-khdour
Java Thread Programming
Events and Event Handling
Multithreaded Programming in Java
Interfaces and Inheritance
ITEC324 Principle of CS III
21 Threads.
Border Layout, using Panels, Introduction to PinBallGame
Expanding the PinBallGame
ITEC324 Principle of CS III
Chapter 6 Inheritance.
Presentation transcript:

Chapter 7: Pinball Game Construction Kit

Vectors Example of a “collection class” Must “import java.util.Vector” More flexible than arrays: will grow Define: private Vector balls; Init: balls = new Vector(); Add an entry: balls.addElement(b1); Access: balls.elementAt(i); How many entries: balls.size();

Vectors (contd) Can only hold objects, not primitives: int I = 17; Balls.addElement(i); // NOT POSSIBLE Balls.addElement( new Integer(i)); // OK Internally: uses Object[] array, therefore must cast elements after retrieval: PinBall aBall = (PinBall) balls.elementAt(i);

MouseListener Interface public interface MouseListener { public void mouseClicked(MouseEvent e); public void mouseEntered(MouseEvent e); public void mouseExited(MouseEvent e); public void mousePressed(MouseEvent e); public void mouseReleased(MouseEvent e); }

Adapter class (library supplied) public class MouseAdapter implements MouseListener { public void mouseClicked(MouseEvent e) {} … } All five methods don’t do anything, but we can define a subclass overriding just those we really want: public class MouseKeeper extends MouseAdapter { public void mousePressed(MouseEvent e) { … // some code }}

More on MouseKeeper So MouseKeeper is a subclass of MouseAdapter, therefore implements the interface MouseListener, so we can: addMouseListener( new MouseKeeper()); MouseEvent: provides useful methods like getX() and getY() to determine the mouse position at the occurrence of the event: e.g. mouseReleased() => release position

Multiple Threads of Execution Previous chapters: animation was a loop inside paint(g) method, now we explicitly create a separate thread A thread is like a parallel process, but inside the same memory address space Creation: subclassing builtin Thread class

PinBallThread extends Thread { private Ball = theBall; public PinBallThread (Ball aBall) { // CONSTRUCTOR theBall = aBall;} public void run() { // RUN METHOD while (theBall.y() < FrameHeight) { theBall.move(); repaint(); try { sleep(10); } catch (InterruptedException e) {System.exit(0); }}}

How to create Must generate Ball and Thread, and start explicitly: PinBall newBall = new PinBall(x,y); balls.addElement(newBall); Thread newThread = new PinBallThread(newBall); newThread.start(); Don’t call run() directly.

Exception handling try { sleep(10); } catch (InterruptedException e) {System.exit(0); } An Exception:an error condition that we can catch and handle systematically If some method (like sleep()) can throw an exception, we need to wrap it inside a try block (or declare that our method might throw on this exception; see the GuessingGame IO for another example)

PinBallTarget interface Want a uniform way of handling all the various targets Same behavior, but different structures: interface PinBallTarget { public boolean intersects (Ball aBall); public void moveTo(int x, int y); public void paint(Graphics g); public void hitBy(Ball aBall); }

Various targets Both Balls and Targets use Rectangle, which defines an intersects() method See how Spring, Wall, and Hole implement the interface PinBallTarget But Hole also extends Ball, and ScorePad extends Hole, overriding e.g. paint() and hitBy() Structural relationship => behavioral relationship, but not always vice versa; if just behavioral relationship: use interface

Class Label Another AWT supplied class: scoreLabel = New label(“Score = 0”); scoreLabel.setText(“Score = “ + score); What if two (or more) threads want to update the score simultanously? Must ensure update happens as one single step (socalled “atomic action”) One Java way: synchronized methods

Synchronized methods Never executed in parallel by multiple threads, will always be sequenced somehow, i.e. one thread executes all the method, then the next thread, … synchronized public void addScore (int v) { score = score + v; scoreLabel.setText(“Score = “ + score); }

Dynamic construction: More interesting if we can build up the pinball layout at runtime Rewrite MouseKeeper class: Have a pallet of targets If mousePressed() there, and mouseReleased() inside the target area, then put an appropriate target there Communication uses data member element

Polymorphism A variable/parameter/data member declared some type can actually hold a subtype as well, e.g.: public void hitBy(Ball aBall) { … } but the actual Ball is really a PinBall (which extends Ball) Also interface can be used as type: PinBallTarget target = (PinBallTarget) targets.elementAt(j); but actually Wall, etc. (which implements PinBallTarget)

Summary Used collection class Vector MouseListener/MouseAdaptor Multiple Threads Exceptions Interface vs. inheritance Polymorphism: Ball / PinBall, …