AP Computer Science Unit 13. Still More Graphics and Animation.

Similar documents
AP CS Unit 12: Drawing and Mouse Events

Advanced Java Unit 6: Review of Graphics and Events

Method Of Key Event Key Listener must implement three methods, keypressed(), keyreleased() & keytyped(). 1) keypressed() : will run whenever a key is

AP CS Unit 11: Graphics and Events

Graphical User Interfaces 2

H212 Introduction to Software Systems Honors

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing.

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline

public void mouseexited (MouseEvent e) setminute(getminute()+increment); 11.2 public void mouseclicked (MouseEvent e) int x = e.getx(), y = e.gety();

CS 251 Intermediate Programming GUIs: Event Listeners

Programmierpraktikum

G51PRG: Introduction to Programming Second semester Applets and graphics

The AWT Event Model 9

Graphical User Interfaces 2

(listener)... MouseListener, ActionLister. (adapter)... MouseAdapter, ActionAdapter. java.awt AWT Abstract Window Toolkit GUI

Graphical User Interfaces 2

Programming Languages and Techniques (CIS120)

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

Programming Languages and Techniques (CIS120)

Lecture 3: Java Graphics & Events

Java Foundations John Lewis Peter DePasquale Joe Chase Third Edition

Event Driven Programming

Inheritance. One class inherits from another if it describes a specialized subset of objects Terminology:

Lecture 5: Java Graphics

CSIS 10A Assignment 14 SOLUTIONS

CSE 331 Software Design & Implementation

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

PIC 20A GUI with swing

OBJECT ORIENTED PROGRAMMING. Course 8 Loredana STANCIU Room B613

1.00/1.001 Introduction to Computers and Engineering Problem Solving Spring Quiz 2

Lecture 19 GUI Events

Java for Interfaces and Networks (DT3010, HT10)

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created.

Unit 7: Event driven programming

EXCEPTIONS & GUI. Errors are signals that things are beyond help. Review Session for. -Ankur Agarwal

CS 201 Advanced Object-Oriented Programming Lab 10 - Recursion Due: April 21/22, 11:30 PM

Lab 10: Inheritance (I)

Name: Checked: Learn about listeners, events, and simple animation for interactive graphical user interfaces.

CS 106A, Lecture 14 Events and Instance Variables

CSE 331 Software Design and Implementation. Lecture 19 GUI Events

CS2110. GUIS: Listening to Events

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

SAMPLE EXAM Exam 2 Computer Programming 230 Dr. St. John Lehman College City University of New York Thursday, 5 November 2009

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events

BASICS OF GRAPHICAL APPS

2IS45 Programming

Object-oriented programming in Java (2)

Advanced Java Programming (17625) Event Handling. 20 Marks

Java GUI Design: the Basics

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

GUI in Java TalentHome Solutions

Events. Dispatch, event-to-code binding. Review: Events Defined 1/17/2014. occurrence.

CS 106A, Lecture 14 Events and Instance Variables

Computer Science II - Test 2

The init() Method. Browser Calling Applet Methods

GUI Event Handlers (Part I)

Using Methods. Methods that handle events. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

GUI Event Handling 11. GUI Event Handling. Objectives. What is an Event? Hierarchical Model (JDK1.0) Delegation Model (JDK1.1)

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

UNIT-3 : MULTI THREADED PROGRAMMING, EVENT HANDLING. A Multithreaded program contains two or more parts that can run concurrently.

Heavyweight with platform-specific widgets. AWT applications were limited to commonfunctionality that existed on all platforms.

IT101. Graphical User Interface

Windows and Events. created originally by Brian Bailey

Which of the following syntax used to attach an input stream to console?

Introduction This assignment will ask that you write a simple graphical user interface (GUI).

2. (True/False) All methods in an interface must be declared public.

CSC 160 LAB 8-1 DIGITAL PICTURE FRAME. 1. Introduction

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

COMPSCI 230. Software Design and Construction. Swing

Computer Science 210: Data Structures. Intro to Java Graphics

PESIT Bangalore South Campus

CS2110. GUIS: Listening to Events

Dr. Hikmat A. M. AbdelJaber

Handling Mouse and Keyboard Events

THE UNIVERSITY OF AUCKLAND

Graphical User Interface (GUI)

GUI 4.1 GUI GUI MouseTest.java import javax.swing.*; import java.awt.*; import java.awt.event.*; /* 1 */

CS2110. GUIS: Listening to Events Also anonymous classes versus Java 8 functions. Anonymous functions. Anonymous functions. Anonymous functions

CS2110. GUIS: Listening to Events. Anonymous functions. Anonymous functions. Anonymous functions. Checkers.java. mainbox

ANSWER KEY Exam 2 Computer Programming 230 Dr. St. John Lehman College City University of New York Thursday, 5 November 2009

CS 201 Advanced Object-Oriented Programming Lab 3, Asteroids Part 1 Due: February 17/18, 11:30 PM

Programming Languages and Techniques (CIS120)

I/O Framework and Case Study. CS151 Chris Pollett Nov. 2, 2005.

MIT AITI Swing Event Model Lecture 17

Graphical User Interface (GUI)

Event Binding. Different Approaches Global Hooks. 2.5 Event Binding 1

Lecture 28. Exceptions and Inner Classes. Goals. We are going to talk in more detail about two advanced Java features:

Java Mouse Actions. C&G criteria: 5.2.1, 5.4.1, 5.4.2,

OOP Assignment V. For example, the scrolling text (moving banner) problem without a thread looks like:

Come & Join Us at VUSTUDENTS.net

Block I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1

Class 16: The Swing Event Model

Programming via Java User interaction

Introduction to the JAVA UI classes Advanced HCI IAT351

COSC 123 Computer Creativity. Graphics and Events. Dr. Ramon Lawrence University of British Columbia Okanagan

Events Chris Piech CS106A, Stanford University. Piech, CS106A, Stanford University

Twin A Design Pattern for Modeling Multiple Inheritance

Class 27: Nested Classes and an Introduction to Trees

Transcription:

AP Computer Science Unit 13. Still More Graphics and Animation. In this unit you ll learn about the following: Mouse Motion Listener Suggestions for designing better graphical programs Simple game with modeling classes and view classes Keyboard Listener ****************************************** If we want to detect if the user is moving the mouse, then we need to know about the MouseMotionListener interface. It has two methods: void mousedragged(mouseevent e) void mousemoved(mouseevent e) Often we use this with the events handled by the MouseListener interface. Copy and run the first program which consists of the RunMotionFrame and MotionPanel classes. As you move the mouse, points are added to an array list and drawn as circles. If you drag the mouse, nothing should appear. If the user moves the mouse off the panel and then back onto the panel, the array list is cleared. Notice that I moved the main method into the RunMotionFrame class. This is neither better nor worse (in my opinion) that keeping the main method in its own class. The code for these two classes is on the next page. 1

import javax.swing.*; import java.awt.*; public class RunMotionFrame extends JFrame { public static void main(string[] args) { RunMotionFrame f = new RunMotionFrame(); f.display(); public RunMotionFrame(){ setdefaultcloseoperation(exit_on_close); settitle( "Graphics" ); MotionPanel mp = new MotionPanel(); mp.setpreferredsize(new Dimension(400, 400)); getcontentpane().add( mp ); pack(); public void display() { EventQueue.invokeLater(new Runnable() { public void run() { setvisible(true); ); Notice: addmousemotionlistener( eek ); Notice: implements both listeners import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.arraylist; public class MotionPanel extends JPanel { private ArrayList<Point> pts = new ArrayList<Point>(); public MotionPanel() { setbackground( Color.ORANGE ); setborder( BorderFactory.createLineBorder(Color.BLACK ) ); Eek eek = new Eek(); addmousemotionlistener( eek ); addmouselistener( eek ); @Override public void paintcomponent( Graphics g ) { super.paintcomponent( g ); for ( Point p : pts ) g.filloval( p.x-5, p.y-5, 10, 10 ); private class Eek implements MouseListener, MouseMotionListener{ public void mouseentered( MouseEvent e ){ pts.clear(); repaint(); public void mousepressed( MouseEvent e ){ public void mousereleased( MouseEvent e ) { public void mouseexited( MouseEvent e ){ public void mouseclicked( MouseEvent e ){ public void mousedragged( MouseEvent e ){ public void mousemoved( MouseEvent e ){ int x = e.getx(); int y = e.gety(); pts.add( new Point( x, y ) ); repaint(); Notice that the Eek class implements both interfaces and therefore needs to have seven methods, even though it only uses two methods. The MouseAdapter class is an abstract class that implements both the MouseListener and MouseMotionListener interfaces (it also implements the MouseWheelListener interface). These methods in MouseAdapter do nothing. We can simplify the Eek class by making it a subclass of MouseAdapter and then overriding those methods that we actually need. This is shown on the next page. 2

private class Eek extends MouseAdapter{ @Override public void mouseentered( MouseEvent e ){ pts.clear(); repaint(); @Override public void mousemoved( MouseEvent e ){ int x = e.getx(); int y = e.gety(); pts.add( new Point( x, y ) ); repaint(); As you can see this is a lot cleaner than the earlier approach. ALERT. You should always use the @Override notation when extending MouseAdapter. Please remind me to say why (as opposed to earlier when we were implementing an interface and it was not as important to use @Override.) Program 1. When the user presses their mouse on a panel, a point appears. As they drag the mouse a line goes from where they pressed to their current location. When the mouse is released, the line is finished. If they press the mouse again, the old line disappears and a new line starts to appear. There are two of these panels in the frame. The inner class should extend MouseAdapter. To generate a thicker line, do the following in the paintcomponent method: Graphics2D g2 = (Graphics2D) g; g2.setstroke(new BasicStroke(5)); g2.drawline(x1, y1, x2, y2 ); Graphics2D is a subclass of the Graphics class so it inherits all the methods of Graphics and adds some new ones as well. Program 2. Similar to exercise 1 except there s an array of points so you can draw pictures (as long as it is all straight lines). If the user right-clicks on a panel, everything is erased. 3

Good Design. When you are developing a program that has a graphical interface, it is a very good idea to have some classes whose main responsibility is to display information to the user and other classes that are responsible for modeling the underlying behavior of the program. Example: In this program there are circles moving around the panel at different speeds. When they hit the sides of the panel, they bounce off the walls. Program 3. There are two panels that do the same thing. If the user drags the mouse in a panel, circles are generated and start moving around the panel and bouncing off the walls. If the user moves the mouse (but not dragging) over a circle, the circle is removed. When the mouse exits the panel, the circles stop moving. If the mouse enters the panel, the circles start moving again. The Circle class represents a circle that has a center, color, and velocity. In the version below, the circle only moves left or right. Later you will modify the class so that the circles move in the y direction as well. import java.awt.*; import java.awt.geom.*; // needed for the Point2D and Point2D.Double classes public class Circle{ private double x, y; // coordinates of the circle s center private double dx; // speed in the x direction public static final int RADIUS = 10; private Color color; public Circle( double x, double y ){ this.x = x; this.y = y; dx = 5*Math.random() + 2; if (Math.random() < 0.5 ) dx = -dx; int red = (int)(256*math.random()); int green = (int)(256*math.random()); int blue = (int)(256*math.random()); int alpha = (int)(256*math.random()); color = new Color( red, green, blue, alpha ); 4

public void draw( Graphics g ){ Draw a circle with the given center and radius. The edge of the circle should be black and use the color variable for the fill. public Point2D getcenter(){ return new Point2D.Double( x, y ); public boolean contains( Point2D p ){ double diffx2 = (p.getx() - this.x)*(p.getx() - this.x); double diffy2 = (p.gety() - this.y)*(p.gety() - this.y); return diffx2 + diffy2 <= RADIUS*RADIUS; public void updatelocation(){ x += dx; public void changelocation( double x1, double y1 ){ x = x1; y = y1; public double getdx(){ return dx; public void setdx( double d ){ dx = d; Point2D is an abstract class. Point2D.Double is a static nested class of Point2D that extends Point2D The contains method returns true if the p is a point within the circle. We do not take the square root because it is faster to compare the distance^2 values public void slowdown( double amt ){ amt = Math.abs( amt ); if ( Math.abs( dx ) <= amt ) dx = 0; else if ( dx > 0 ) dx = dx - amt; else dx = dx + amt; if ( Math.abs( dx ) < 0.1 ) dx = 0; The slowdown method decreases the circle s speed by whatever value amt is. This method is not used in exercise 3 but it is used in exercise 4. 5

The Environment class represents a collection of circles moving in a frictionless rectangular enclosure. import java.util.arraylist; import java.awt.*; import java.awt.geom.*; public class Environment{ private int width, height; // size of the rectangular space private ArrayList<Circle> list = new ArrayList<Circle>(); public Environment( int w, int h ){ width = w; height = h; public void add( int x, int y ){ list.add( new Circle( x, y ) ); public void update( ){ for ( Circle c : list ){ c.updatelocation(); Point2D loc = c.getcenter(); if ( loc.getx() <= 0 loc.getx() >= width ) c.setdx( -c.getdx() ); The update method calls each Circle s updatelocation method. Then it determines if the circle has moved too far left or right. If it has, it flips the circle s velocity from positive to negative or negative to positive as appropriate. public void delete( Point p ){ for ( int k = list.size() - 1; k>= 0; k-- ){ if ( list.get( k ).contains( p ) ) list.remove( k ); public void draw( Graphics g ){ for ( Circle c : list ) c.draw( g ); IMPORTANT. Notice in the design of the Circle and Environment classes, they are not dependent on how they will be shown to the user. We could show them as JLabels or we call the draw method and display them on a JPanel. This makes them easier to code and use. 6

Here is the beginning of the Ex3_Panel class that displays the circles: public class Ex3_Panel extends JPanel { private Environment env; private javax.swing.timer timer; public Ex3_Panel( int width, int height ) { env = new Environment( width, height ); setbackground( Color.WHITE ); setborder( BorderFactory.createLineBorder(Color.BLACK ) ); Eek eek = new Eek(); addmousemotionlistener( eek ); addmouselistener( eek ); timer = new javax.swing.timer( 40, new TimerListener() ); timer.start(); @Override public void paintcomponent( Graphics g ) { super.paintcomponent( g ); env.draw( g ); Write the TimerListener class. Its sole method contains two lines of code. The second line is: repaint(); Write the Eek class which extends MouseAdapter. Each method is no more than two lines long. Whenever the mouse is dragged in the panel, add circles at the mouse s location. Whenever the mouse is moved (not dragged) in the panel, remove any circles that the mouse is over. If the mouse exits the panel, stop the timer. If the mouse enters the panel, start the timer. Write a class that extends JFrame and contains two instances of the Ex3_Panel class. After you get this working, go back to the Circle class and change it so a circle also moves in the y direction. This means: (1) adding another instance variable; (2) changing the constructor; (3) changing the updatelocation method; (4) adding mutator and accessor methods for the new instance variable; and (5) modifying the slowdown method. You will also need to modify the Environment class by changing its update method. 7

Program 4. This exercise is a variation on the work you did in exercise 3. When the user drags the mouse on a panel, moving circles are added to the panel. However, these circles gradually slow down. When they stop moving they are removed from the panel. The timer for each panel starts when the panel is instantiated and never stops. There are also JLabels below the panels which indicate the number of circles currently in the panel. Use the same Circle class from exercise 3 (with circles moving in both the x and y directions). Write the Friction_Env class which is identical to the Environment class from Exercise 3 except: 1) Add the following method public int numcircles(){ returns the number of circles in the panel 2) Change the update method as follows. public void update( ) Iterate through the list of Circle objects and call each Circle s slowdown method. I suggest you use an argument of 1.0 or less. If a Circle s speed in the x and y directions are both zero, remove that Circle. Call the updatelocation method for all the remaining Circles. Make sure to change a Circle s velocities if it hits one of the walls. The JLabels should NOT be part of the class that extends JPanel and displays the Circles. I suggest that whenever the Timer object generates an action event (in the panel subclass), you update the text on the corresponding JLabel (that s in the class that extends JFrame). 8

Last Program. Here we will make a simple game. We move a player around a panel using the arrow keys. You get 10 points for every blue heart you catch. Your health decreases each time you hit the star-like images. You die on the third hit and the game stops. Here is the basic design. There are six classes. RunGame simply contains the main method that we ve been using. GameFrame extends JFrame. It creates a button (at the top), a label (at the bottom), and a GamePanel (in the middle). It also contains a timer and a Game object. GamePanel extends JPanel. This contains a reference to the same Game object that the GameFrame class created. It draws all the objects in the game. The GamePanel also contains a KeyListener that controls how the Player object moves. The Player class models the concept of something/someone moving around the field. It has a location, speed, and health attributes (as well as other attributes). The Guy class models the concept of things moving from right to left across the field. Some Guy objects are good meaning the player should try to get them. Some Guy objects are bad meaning the player should try to avoid them. The Game class models the game s behavior. It contains a Player object and an array list of Guy objects. Important: the GameFrame and GamePanel classes only communicate with the Game object; they never directly communicate with the Player or Guy classes. It has an update method that is called every time the Timer fires off an Action event. In this update method: o the player s move method is called o new Guy objects are spawned o each Guy object is moved o collisions between the player and Guy objects are detected o Guy objects that have moved off the left edge of the panel are removed Copy the files and complete the methods. Download the images. If using BlueJ, put the images in the folder with the java files. If using Eclipse, put the images in the folder than contains the scr and bin folders. Please change the images, speeds, etc. to make the game more interesting to you. Just don t make major changes to the overall design without first discussing it with me. The KeyListener code is discussed on the next page. 9

Some words about Key Listener code in this project. The KeyListener interface has three methods. void keypressed(keyevent e) Invoked when a key has been pressed. void keyreleased(keyevent e) Invoked when a key has been released. void keytyped(keyevent e) Invoked when a key has been typed. KeyAdapter is an abstract class that implements the KeyListener interface with three empty methods (same concept as the MouseAdapter class). In this program the inner class extends KeyAdapter. The KeyEvent has a getkeycode method that tells us which key generated the event. Problem. When a key is pressed, a KeyEvent is generated then there is a short pause and then more KeyEvents are generated. For example, if the M key were pressed it would seem like: M (short delay) MMMMMMMMMMMMMM. In a game situation, we don t want that short delay. Also, we need to detect if two or more keys are simultaneously being pressed. The solution is to keep a list of which keys are currently being pressed. So there is an array of boolean values - if an element is true, then that key is currently being pressed. Every time there a key event is generated, the game is notified so that the player s position can be updated. IMPORTANT. When working with a key listener, you must understand the concept of focus. Imagine this situation. There are two text fields and you hit the A key. Where does the A appear? Answer: in the field that has the focus - indicated by a blinking cursor. Only one object can have the focus at any time. So in this focus we need to make sure the GamePanel gets the focus during game play. Here s how we accomplish this. Step one. In the GamePanel constructor we have this statement. setfocusable(true); This means that the panel can get the focus. Step two. When the Program is first displayed, the button will get the focus. However, when the button is clicked (to start the game), we want the focus to shift to the game panel - so that the code we wrote in that class (which handles key events) will actually react to key events. So we add this statement at the end of the actionperformed method. gp.requestfocusinwindow(); This shifts the focus to the game panel, gp. Note. Key Bindings are generally preferred to Key Listeners but since Key Listeners follow the same approach you ve seen with Action Listeners and Mouse Listeners, that s the approach I ve used here. If you are interested in learning about Key Bindings, go ahead and look up some tutorials. 10