Multimedia in Java Multimedia combines graphics, animation and sound

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

Computer Science 209 Images and GUIs. Working with Java Colors The class java.awt.Color includes constants, such as Color.red, for some commonly used.
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.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Multithreading : animation. slide 5.2 Animation Animation shows different objects moving or changing as time progresses. Thread programming is useful.
1 Frameworks. 2 Framework Set of cooperating classes/interfaces –Structure essential mechanisms of a problem domain –Programmer can extend framework classes,
Event Handling Events and Listeners Timers and Animation.
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.
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.
Introduction to GUI Java offers a great number of pre-defined classes to support the development of graphical user interfaces –These are broken down into.
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.
(c) 2008 E.S.Boese All Rights Reserved. Threads and Media Chapter 8 - Lecture Slides 1.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 20.1 Test-Driving the Screen Saver Application.
CS12420 – Swing and threads Lynda Thomas
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,
Adding Graphics to a Frame Application Applets: Can generate drawings by overriding paint Frame: Do not draw directly on a frame. Draw graphics on a JPanel.
KeyListener and Keyboard Events Another type of listener listens for keyboard entry – the KeyListener which generates KeyEvents –to implement KeyListener,
GUI Components and Design Here we add one more component to our programs, JButtons –JButtons can only be inserted into JPanels (or JApplets) –Clicking.
Java Event Handling CSIS 3701: Advanced Object Oriented Programming.
CS 112 Department of Computer Science George Mason University CS 112 Department of Computer Science George Mason University Writing Graphic Applications.
J McQuillan SE204: 2004/2005: Lecture 4slide 1 The Graphics Class Used when we need to draw to the screen Two graphics classes –Graphics –Graphics2D.
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
 2000 Prentice Hall, Inc. All rights reserved. Java Multimedia: Images, Animation, Audio and Video Outline 30.1 Introduction 30.2Loading, Displaying and.
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.
Concurrent Programming and Threads Threads Blocking a User Interface.
Java Programming Working with Sound and Images. Topics Learn about the paint() and repaint() methods Learn about paintComponent() method Use the drawString()
Introduction Multimedia –Use of sound, image, graphics and video –Makes applications “come alive”
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
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.
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.
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.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 27.1 Test-Driving the Drawing Shapes Application.
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,
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.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
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.
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.
Java Visual Applications CSIS 3701: Advanced Object Oriented Programming.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
Chapter 4 Interface Types and Polymorphism Part 2.
Modular Event Handling
GUIs and Events Rick Mercer.
Contacts: Intro to game programming in Java (with almost-drawingpanel)
Lecture 10 Graphics D&D 3.14, 4:10, 5.13, 6.15, 8.16, Date.
A First Look at GUI Applications
Lecture 09 Applets.
Java Programming JFileChooser AudioPlayer2 Timer RandomAccessFile
Chapter 4 Interface Types and Polymorphism Part 2
Ellen Walker Hiram College
MVC Paradigm The MVC paradigm breaks applications or interfaces into three parts: the model, the view, and the controller. A --> 25 % B --> 60 % C -->
עקרונות תכנות מונחה עצמים תרגול 7: אנימציה
Drawing in Java.
Events, Event Handlers, and Threads
9. Threads SE2811 Software Component Design
עקרונות תכנות מונחה עצמים תרגול 7: אנימציה
9. Threads SE2811 Software Component Design
Presentation transcript:

Multimedia in Java Multimedia combines graphics, animation and sound Since we’ve already spent time dealing on computer graphics, so we will focus on animation and sound To perform animation, 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 we implement an ActionListener to handle the ActionEvent as we did with JButtons ActionEvent is handled by implementing an actionPerformed method in the case of animation, the actionPerformed method may only have to add 1 to the x or y coordinate of the item we are drawing, and then call repaint( )

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 usually just use this and implement actionPerformed in our class whenever possible (this may not be easy if we also implement an ActionListener in this class to handle JButtons import java.awt.event.*; add “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 Timer Skeleton

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 a Game Object 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)

Handling Multiple ActionEvents private static class ExamplePanel extends JPanel implements ActionListener { private Timer t; private JButton b; public ExamplePanel( ) t = new Timer(1000, this); t.start(); b = new JButton("Button"); b.addActionListener(this); add(b); } public void actionPerformed(ActionEvent e) if(e.getSource( )= =t) System.out.println("Timer pulsed"); else if(e.getSource( )= =b) System.out.println("Button pressed");

Moving Multiple Items How would a game like Asteroids work? we need to keep track of the <x, y> 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)

Sound/Music Just as Java has a facility for displaying an image using the ImageIcon class, you can also play sounds/music this facility is only available through the Applet class or through an IO class created by Sun The harder way: import java.applet.* create a nested inner class that extends Applet, include an instance data of type AudioClip and in the Applet constructor, instantiate an Applet object: aClip = Applet.newAudioClip(getClass( ).getResource(filename)); add an accessor method to your Applet to return the audio clip The slightly easier way: import java.io.*; and sun.audio.*; create objects of types InputStream and AudioStream and then tell the AudioPlayer class to play your AudioStream

import java.applet.*; // needed to generate an AudioClip public class AudioExample2 { public static void main(String[] args) AClip a = new AClip(); // create an Applet AudioClip c = a.getClip(); // use the Applet to generate an AudioClip c.play( ); // play the AudioClip } private static class AClip extends Applet // Applet as an inner class used to { // generate AudioClip objects private static AudioClip a; // Our AudioClip public AClip() // constructor a = Applet.newAudioClip(getClass( ).getResource("chimes.wav")); } // getClass( ) returns the file location of this class // getResource returns the actual item, in this case a wav file public AudioClip getClip() // accessor return a; AudioClip Example

Another Audio Example import java.io.*; // use this to create an InputStream import sun.audio.*; // another class that can be used to play audio public class AudioExample2 { public static void main(String[ ] args) try // create an AudioStream of the wav file InputStream in = new FileInputStream("chimes.wav"); AudioStream as = new AudioStream(in); // play the AudioStream AudioPlayer.player.start(as); // use the following instead to play the wav file repeatedly in a continuous loop //AudioData data = as.getData(); //ContinuousAudioDataStream cas = // new ContinuousAudioDataStream (data); //AudioPlayer.player.start(cas); } catch(IOException ex) { // any code here will be used if trying the audio player doesn’t work!}