Animation To animate our programs, that is, to have real time interactions where objects move on the screen, we want to call repaint( ) every few milliseconds.

Slides:



Advertisements
Similar presentations
2D Graphics Drawing Things. Graphics In your GUI, you might want to draw graphics E.g. draw lines, circles, shapes, draw strings etc The Graphics class.
Advertisements

Web Design & Development Lecture 19. Java Graphics 2.
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.
Graphics You draw on a Graphics object The Graphics object cannot directly be created by your code, instead one is generated when the method paintComponent.
Chapter 4 (Horstmann’s Book) Interface Types and Polymorphism: Graphics, Timer, Animation Hwajung Lee.
Multithreading : animation. slide 5.2 Animation Animation shows different objects moving or changing as time progresses. Thread programming is useful.
More Java Drawing in 2D Animations with Timer. Drawing Review A simple two-dimensional coordinate system exists for each graphics context or drawing surface.
Event-Driven Programming Thus far, our programs have been executed one statement after the other However, many programs depend on user actions to dictate.
Event Handling Events and Listeners Timers and Animation.
CS 280 Data Structures Professor John Peterson. Quiz 4 Recap Consider the following array: {2, 6, 7, 3, 4, 1, 5, 9}. Draw this in tree form and then show.
Lecture 24 Applets. Introduction to Applets Applets should NOT have main method but rather init, stop, paint etc They should be run through javac compiler.
Carnegie Mellon University, MISM1 Java GUI programming and Java Threads GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann Thread.
Object Oriented Programming Java 1 GUI example taken from “Computing Concepts with Java 2” by Cay Horstmann GUI Programming.
Programming Task: Task 1 Controlled Assessment Practice.
Animation Most games have moving components, how do we make things move? –We will track the location of an object using an x,y coordinate –We will draw.
Java: Animation Chris North cs3724: HCI. Animation? Changing graphics over time Examples: cartoons Clippy, agents/assistants Hour glass Save dohicky Progress.
Java Programming, 3e Concepts and Techniques Chapter 3 Section 65 – Manipulating Data Using Methods – Java Applet.
Threads and Multimedia Animation, Images, Sound. Animation nAnimation, displaying a sequence of frames to create the illusion of motion, is a typical.
Introducing Graphics There are generally two types of graphics facilities in Java –Drawing –GUIs We concentrate on drawing here We will draw on a Graphics.
1 Event Driven Programming wirh Graphical User Interfaces (GUIs) A Crash Course © Rick Mercer.
Introducing Arrays We will often need to store collections of information –a list of names to sort –a list of values to compute averages, standard deviation,
CS 151: Object-Oriented Design October 3 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 20.1 Test-Driving the Screen Saver Application.
Visual Basic .NET BASICS
CSE 219 Computer Science III Images. HW1 Has been posted on Blackboard Making a Game of Life with limited options.
KeyListener and Keyboard Events Just as we can implement listeners to handle mouse events, we can do the same for keyboard events (keypresses) –to implement.
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,
KeyListener and Keyboard Events Another type of listener listens for keyboard entry – the KeyListener which generates KeyEvents –to implement KeyListener,
Java Event Handling CSIS 3701: Advanced Object Oriented Programming.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
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.
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
Swing GUI Components You can create graphics components to place on your applet using classes available in the Swing package ( javax.swing ) Class names.
MSc Workshop - © S. Kamin, U.Reddy Lect 4 - Events - 1 Lecture 4 – Event Handling r Painting r Event types r Catching different event types.
CSE 219 Computer Science III Image Manipulation. HW 1 Has been posted on Blackboard Making a Game of Life with limited.
 Definition: An event is an object thrown in response to a user of programmatic action  Definition: A listener is a series of methods that executes in.
Concurrent Programming and Threads Threads Blocking a User Interface.
Java Classes, Objects, and Events: A Preview JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria.
CS324e - Elements of Graphics and Visualization Java GUIs - Event Handling.
Animation To animate our programs, that is, to have real time interactions where objects move on the screen, we want to call repaint( ) every few milliseconds.
Graphics basic 1. 2 Objectives Understand Java coordinate systems. Draw things using the methods in the Graphics class. Override the paintComponent method.
Java Dynamic Graphics.
GUI DYNAMICS Lecture 11 CS2110 – Fall GUI Statics and GUI Dynamics  Statics: what’s drawn on the screen  Components buttons, labels, lists, sliders,
Practical Session 10: Animation. Animation kinds There are three basic kinds of animation: 1. Moving object 2. Changing pictures 3. Combination of 1 and.
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.
Arrays and Logic Let’s generate 6 lotto numbers using a loop and the random number generator – but we don’t want to duplicate any numbers – how do we know.
Applets Java code is compiled into byte code instead of machine language –Languages like C, C++, Pascal and others are compiled into machine language so.
Chapter 4 Interface Types and Polymorphism: Graphics, Timer, Animation.
A cannon game ?. Simple version angle from command line, one shot only Coordinate system is “upside-down”: Use dy(int) method to transform y coordinate:
עקרונות תכנות מונחה עצמים תרגול 7: אנימציה. בשבוע שעבר  paint  Graphics  repaint.
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,
CS 5JA Introduction to Java Graphics One of the powerful things about Java is that there is.
1/18H212Mouse and Timer Events H212 Introduction to Software Systems Honors Lecture #16: Mouse and Timer Events October 26, 2015.
GUI Tutorial 2. What did we do last time?  Basic flow  instance variables, set up in ctor, close operation, size, visible  JFrame  Event-driven programming.
KeyListener and Keyboard Events Just as we can implement listeners to handle mouse events, we can do the same for keyboard events (keypresses) –to implement.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Lesson 28: More on the GUI button, frame and actions.
Computer Science I Animations. Bouncing ball. The if statement. Classwork/homework: bouncing something. Compress and upload work to Moodle.
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
5-1 GUIs and Events Rick Mercer. 5-2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces to respond.
Basic Graphics 03/03/16 & 03/07/16 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
Chapter 4 Interface Types and Polymorphism Part 2.
Graphical User Interfaces
Lecture 09 Applets.
Multimedia in Java Multimedia combines graphics, animation and sound
Java Programming: Guided Learning with Early Objects
Events, Event Handlers, and Threads
עקרונות תכנות מונחה עצמים תרגול 7: אנימציה
Presentation transcript:

Animation To animate our programs, that is, to have real time interactions where objects move on the screen, we want to call repaint( ) every few milliseconds –how does our program know when a few milliseconds elapse? –there is a Timer class available –set it for 20 milliseconds and every 20 milliseconds, the Timer generates an ActionEvent In Java, we can have our program listen for an event and when the event arises, have it call a method –in this case, the Timer generates ActionEvents which will then cause a method called actionPerformed to execute –so we have to implement the actionPerformed method

actionPerformed This method will look like this: –public void actionPerformed(ActionEvent e) –{…} What should our actionPerformed method do? –we want to draw something on the Graphics panel and move it every time the Timer sends out an Event –so actionPerformed will “move” the object (change its location) and then call repaint( ) –repaint calls paintComponent –paintComponent first erases whatever had been previously drawn and then draws the object(s) anew, having possibly been moved

Timer class A Timer object is instantiated by: –Timer t = new Timer(duration, handler); duration is the time (in milliseconds) that elapses between Timer- generated events, such as 20 or 50 handler is the object that handles the Timer-generated events – we will use this just like we have for our addActionListener statements –The steps are to add import java.awt.event.*; “implements ActionListener” to our class header instantiate the Timer as t = new Timer(10, this); –but use whatever value you want for the duration, 10 or 20 would be adequate for most applications start the timer by using t.start( ); –if we need to stop the timer, we use t.stop( ); –that’s about all there is to it!

Timer Skeleton import javax.swing.*; import java.awt.event.*; public class TimerSkeleton implements ActionListener { private Timer t; // other instance data go here as needed public TimerSkeleton( ) { t = new Timer(10, this); t.start( ); // other initialization operations go here as needed } // other methods go here as needed public void actionPerformed(ActionEvent e) { // whatever you want to happen when the Timer pulses go here }

What Should actionPerformed Do? This depends on why you are using a Timer –to move an object in a Graphics panel (e.g., a ball) alter the x and y coordinates and call repaint( ) –for a Game: calculate where game objects (say a spacecraft or a missile) have moved and redraw them –this may require the user of an array of x and an array of y values to store the various objects, or multiple variables such as myX, myY, yourX, yourY, or both (the arrays might store the X and Y coordinates of missiles launched from one to the other) –for Animation: if our item being drawn is represented by an array of different figures –then just increment the array index and repaint( ) –we will see an example of a StickFigure, but this could also be done by having a series of jpg or gif files all pre-loaded into an array of Images

Moving an Image to Create Motion Imagine that your class draws on a JPanel an ImageIcon (say of a spaceship) –currently, the spaceship is located at coordinates x, y –the following actionPerformed method will randomly move the spaceship on the screen –x and y should be class variables so that you could do g.drawImage(image, x, y, this); in your paintComponent method public void actionPerformed(ActionEvent e) { int dx = generator.nextInt(2); // generate a # from -1 to +1 int dy = generator.nextInt(2); // generate a # from -1 to +1 x += dx;// move the piece in a random x direction y += dy;// move the piece in a random y direction repaint( );// assume repaint does drawImage at x, y }

Full Example Code public TimerExample( ) { t = new Timer(10, this); t.start( ); x = 150; y = 150; repaint( ); } public void actionPerformed(ActionEvent ev) { int distanceX = generator.nextInt(2)); int distanceY = generator.nextInt(2)); x += distanceX; y += distanceY; repaint( ); } public void paintComponent(Graphics g) { super.paintComponent(g); g.setColor(Color.red); g.fillOval(x, y, 5, 5); } At each Timer Event, randomly move the object (a red circle) up/down/left/right by 0 or 1 unit Note: we could make it more realistic by generating a random int from 1-9 and move it in one of 8 directions or leave it stationary (1 = upper left, or subtract 1 from x and y, 2 = straight up, etc)

Better Motion The random motion from the previous example would make the object on the screen look like a bee, buzzing around What if we wanted a more purposeful movement? For instance in a straight line? Lets add 2 more variables, dx and dy –(delta x means “change in x”, delta y means “change in y”, we use d because we don’t have the Greek letter delta) For actionPerformed, just do x=x+dx; y=y+dy; –If dx=1 and dy=2, then our object will move in a straight line to the right 1 pixel and down 2 pixels at each movement, or a diagonal downward line –If dx=0 and dy=-1, then the object moves straight up –We should also make sure that x & y do not “go off” the screen (if x < 10 make x = 10 and dx = 0 to stop the motion there, or let x = X_SIZE to “wrap around”)

Moving Multiple Items How would a game like Asteroids work? –we need to keep track of the coordinates of multiple values, just like we did with our paint program –so we create an array of x, y, dx and dy int values private int[ ] x, y, dx, dy;// dx, dy – velocity of x, y private int num;// number of items in the arrays –actionPerformed now manipulates all items in the array and paintComponent draws them all public void actionPerformed(ActionEvent e) { for(int i=0;i<num;i++) { x[i]+=dx[i]; y[i]+=dy[i]; } If x[i] or y[i] reaches a boundary (0 or max X/Y) then change dx or dy to be the opposite (multiply by -1)