Introduction Multimedia –Use of sound, image, graphics and video –Makes applications “come alive”

Slides:



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

More Java Drawing in 2D Animations with Timer. Drawing Review A simple two-dimensional coordinate system exists for each graphics context or drawing surface.
1 L45 Multimedia: Applets and Applications. 2 OBJECTIVES  How to get and display images.  To create animations from sequences of images.  To create.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter Java Multimedia: Images, Animation, Audio.
Event Handling Events and Listeners Timers and Animation.
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.
1 Lecturte 14Lecture 7 Applications of Graphics Overview  Conversions Between Applications and Applets  Handling Mouse Events  Handling Keyboard Events.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 19 – Multimedia: Images, Animation and Audio Outline 19.1 Introduction 19.2 Loading, Displaying.
Slides prepared by Rose Williams, Binghamton University Chapter 20 Java Never Ends.
Enahnced Digital Clock Applet Setting applet parameters in the web page. The applet tag in HTML:
1 Recitation 11. Applet Applets. An applet is a Java program that is started by a browser (e.g. netscape or internet explorer) when an html file has a.
Audio Chapter 17 - Student. (c) 2005 by Elizabeth Sugar Boese Audio Files Java can play the following audio types: .au (Sun Audio) .wav (Windows Wave)
 2000 Prentice Hall, Inc. All rights reserved. Java Multimedia: Images, Animation, Audio and Video Outline 30.1 Introduction 30.2Loading, Displaying and.
Unit 071 Review of Applets Learning Outcomes oDistinguish between Java Applications and Java Applets. oWrite applet programs that can load images and play.
 Pearson Education, Inc. All rights reserved Multimedia: Applets and Applications.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
1 Features of Java CS 3331 Fall Outline  Abstract class  Interface  Application --- animation applets.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 16 - Multimedia: Images, Animation, Audio and Video Outline 16.1 Introduction 16.2Downloading the.
Computer Science [3] Java Programming II - Laboratory Course Lab 7: Multimedia: Applets and Applications Faculty of Engineering & IT Software Engineering.
Introduction Multimedia –Use of sound, image, graphics and video –Makes applications “come alive”
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
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.
 2005 Pearson Education, Inc. All rights reserved Multimedia: Applets and Applications.
 2002 Prentice Hall, Inc. All rights reserved. Chapter 18 – Multimedia: Images, Animation, Audio and Video Outline 18.1 Introduction 18.2 Loading, Displaying.
(c) 2008 E.S.Boese All Rights Reserved. Threads and Media Chapter 8 - Lecture Slides 1.
Internet Software Development Applets Paul J Krause.
Java applet basics, loading & displaying images After this section, you should be able to : –Use the applet tag and applet parameters –Describe what a.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
JAPPLET.
Chapter 17: Applets, Images, and Sound. Objectives Learn about applets Write an HTML document to host an applet Use the init() method Work with JApplet.
GUI programming Graphical user interface-based programming.
Object Oriented Programming Lecture 4: Refactoring, An Applet Example, Idiom - Animation applets, Introduction to the Laboratorial exercise www2.hh.se/staff/jebe/oop2005/
Timer Objects  regularly generates action events at programmer-specified time intervals  Timer class is in javax.swing package  Timer (int delay, ActionListener.
Canvas and Graphics CS 21a. 9/26/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L17: Canvas.
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.
1 Block1 – unit 2 (The Case study in Budd 5-6).  create a small application that uses the Abstract Windowing Toolkit (AWT)  Swing packages to simulate.
 2000 Prentice Hall, Inc. All rights reserved. Java Multimedia: Images, Animation, Audio and Video Outline 30.1 Introduction 30.2Loading, Displaying and.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
CSC 205 – Java Programming II Applet. Types of Java Programs Applets Applications Console applications Graphics applications Applications are stand-alone.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Review of Graphics in Java,
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.
Java Programming Working with Sound and Images. Topics Learn about the paint() and repaint() methods Learn about paintComponent() method Use the drawString()
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.
Intro to Applets. Applet Applets run within the Web browser environment Applets bring dynamic interaction and live animation to an otherwise static HTML.
Introduction to Threads Session 01 Java Simplified / Session 14 / 2 of 28 Objectives Define a thread Define multithreading List benefits of multithreading.
1 GUI programming Graphical user interface-based programming Chapter G1 (pages )
Features of Java CS 3331 Sections and 5.5.
CSI 3125, Preliminaries, page 1 Applet. CSI 3125, Preliminaries, page 2 Graphics Methods public abstract void drawString(String str, int x, int y): is.
Chapter 4 Interface Types and Polymorphism: Graphics, Timer, Animation.
Creating a Java Application and Applet
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 27.1 Test-Driving the Drawing Shapes Application.
More OOP. Extending other’s classes extend Java platform classes, e.g. class Applet public class MyApplet extends Applet { public void init() { } public.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 10.
1/18H212Mouse and Timer Events H212 Introduction to Software Systems Honors Lecture #16: Mouse and Timer Events October 26, 2015.
Lesson 28: More on the GUI button, frame and actions.
Java Applets Adding Animation. Import Files You still need to include the same files: –import java.applet.*; –import java.awt.*;
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 28.1 Java Speech API 28.2 Downloading and.
Mouse, Keyboard, Sounds, and Images JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin,
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 7 ( Book Chapter 14) GUI and Event-Driven Programming.
Introduction to Graphics
Lecture 09 Applets.
Multimedia in Java Multimedia combines graphics, animation and sound
Chapter 13: Advanced GUIs and Graphics
עקרונות תכנות מונחה עצמים תרגול 7: אנימציה
Advanced GUIs and Graphics
Presentation transcript:

Introduction Multimedia –Use of sound, image, graphics and video –Makes applications “come alive”

Introduction (cont.) We will focus on –Image-manipulation basics –Creating smooth animations –Customizing animation applets –Creating image maps –Playing audio files (via AudioClip interface)

Loading, Displaying and Scaling Images Demonstrate some Java multimedia capabilities –java.awt.Image abstract class (cannot be instantiated) Can represent several image file formats –e.g., GIF, JPEG and PNG –javax.swing.ImageIcon Concrete class An implementation of the Icon interface that paints Icons from Images.

LoadImageAndScal e.java Lines 14 and 20 Lines 15 and 21 Line 28 Lines // LoadImageAndScale.java 2 // Load an image and display it in its original size 3 // and scale it to twice its original width and height. 4 // Load and display the same image as an ImageIcon. 5 6 // Java core packages 7 import java.applet.Applet; 8 import java.awt.*; 9 10 // Java extension packages 11 import javax.swing.*; public class LoadImageAndScale extends JApplet { 14 private Image logo1; 15 private ImageIcon logo2; // load image when applet is loaded 18 public void init() 19 { 20 logo1 = getImage( getDocumentBase(), "logo.gif" ); 21 logo2 = new ImageIcon( "logo.gif" ); 22 } // display image 25 public void paint( Graphics g ) 26 { 27 // draw original image 28 g.drawImage( logo1, 0, 0, this ); // draw image scaled to fit width of applet 31 // and height of applet minus 120 pixels 32 g.drawImage( logo1, 0, 120, 33 getWidth(), getHeight() - 120, this ); 34 Objects of class Image must be created via method getImage Objects of class ImageIcon may be created via ImageIcon constructor Method drawImage displays Image object on screen Overloaded method drawImage displays scaled Image object on screen

LoadImageAndScal e.java (Part 2) Line 36 Program Output 35 // draw icon using its paintIcon method 36 logo2.paintIcon( this, g, 180, 0 ); 37 } } // end class LoadImageAndScale Method paintIcon displays ImageIcon object on screen Size of the applet: 340 x 340

Java keyword - this this is a reference to the current object — the object whose method or constructor is being called. –pass a reference to the current object as a method parameter g.drawImage( logo1, 0, 0, this ); –distinguish among the parameters private int x; public void setX(int x){ this.x=x; }

Animation Animation shows different objects moving or changing as time progresses Often achieved by launching one or more threads that compute how parts of the animation change Can use Swing Timer class for simple animations More advanced animations are best implemented with thread

Timer for animation Java ’ s Timer class (from javax.swing package) generates a sequence of action events, spaced at equal intervals Timer constructor requires two arguments: –delay time (in milliseconds) –action listener to handle the event triggered by the Timer Useful for animation

Animation Animation involves painting and repainting the same scene, giving the viewer the illusion of a moving picture Two repeated actions can accomplish this –draw a shape –move the shape Example: A random moving ball

import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.util.*; import javax.swing.Timer; public class MovingImage extends JFrame { private Container container; private Timer timer; // changes picture once per second private Random rand; // provides random image locations private ImageIcon imageBall; // the “moving” image public MovingImage() { super("Moving imageIcon"); container = this.getContentPane(); rand = new Random(); imageBall = new ImageIcon("ball.jpg"); timer = new Timer(1000, new ActionListener () { public void actionPerformed(ActionEvent event) { repaint(); } }); timer.start(); }

public void paint (Graphics g) { g.setColor(Color.WHITE); g.fillRect(0,0,200,200); imageBall.paintIcon(container, g, rand.nextInt(150), rand.nextInt(150)); } public static void main(String [] args) { JFrame movingimage = new MovingImage(); movingimage.setSize(200,200); movingimage.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); movingimage.setVisible(true); }

12 Review of Thread Extend the Thread class: –public class MyThread extends Thread {…} –Override public void run( ) –To make it start: MyThread T = new MyThread () ;// create thread T.start(); Implement the Runnable interface: –public class MyRunnable implements Runnable {…} –Must implement public void run( ) –To make it start: MyRunnable r = new MyRunnable() Thread T = new Thread(r); // create thread T.start(); –More flexible For Applet?

import java.applet.Applet; import java.awt.Graphics; public class Anim1a extends Applet implements Runnable { int position = 0; int increment = 3; Thread t; public void start() { if (t == null) { t = new Thread(this); t.start(); } public void stop() { if (t != null) { t.stop(); t = null; } public void paint(Graphics g) { g.fillOval(5, 5 + position, 30, 30); }

public void run() { while (true) { try { Thread.sleep(50); } catch (InterruptedException e) {} position += increment; if (position > 50 || position < 0) increment = -increment; repaint(); }

The version without deprecated stop() method import java.applet.Applet; import java.awt.Graphics; public class Anim1n extends Applet implements Runnable { int position = 0; int increment = 3; Thread t; public void start() { if (t == null) { t = new Thread(this); t.start(); } public void stop() { t = null; } public void paint(Graphics g) { g.fillOval(5, 5 + position, 30, 30); } if (t != null) { t.stop(); t = null; }

public void run() { Thread thisThread = Thread.currentThread(); while (t == thisThread) { try { Thread.sleep(50); } catch (InterruptedException e) {} position += increment; if (position > 50 || position < 0) increment = -increment; repaint(); }

Stopping a Thread Stop animation loop with a flag t == null; //will cleanup thread object Boolean runCondition; while (runCondition) { // run animation }

class Animation extends Thread { private Anim1c appl; private int increment = 3; Animation(Anim1c a) { appl = a; } public void run() { Thread thisThread = Thread.currentThread(); while (this == thisThread) { try { Thread.sleep(50); } catch (InterruptedException e) {} appl.setpos(increment); if (appl.getpos() > 50 || appl.getpos() < 0) increment = -increment; appl.repaint(); }

public class Anim1c extends Applet { private int position = 0; private Thread t; public void start() { if (t == null) { t = new Animation(this); t.start(); } public int getpos() { return position; } public void setpos(int a) { position += a; } public void stop() { if (t != null) { t.stop(); t = null; } public void paint(Graphics g) { g.fillOval(5, 5 + position, 30, 30); }

Multi-threading Multiple parts of the animation –Each part is controlled by a thread

import java.applet.Applet; import java.awt.Graphics; class Animation extends Thread { private Applet appl; protected int increment = 3; protected int position = 0; protected int pause = 50; Animation(Applet a) { appl = a; } public void run() { Thread thisThread = Thread.currentThread(); while (this == thisThread) { try { Thread.sleep(pause); } catch (InterruptedException e) {} position += increment; if (position > 50 || position < 0) increment = -increment; appl.repaint(); } public void draw(Graphics g) { g.fillOval(5, 5 + position, 30, 30); }

class Animation1 extends Animation { Animation1(Applet a) { super(a); increment = 2; pause = 60; } public void draw(Graphics g) { g.fillRect(40 + position, 25, 30, 30); }

import java.applet.Applet; import java.awt.Graphics; public class Anim2a extends Applet { private Animation t, t1; public void start() { if (t == null) { t = new Animation(this); t.start(); } if (t1 == null) { t1 = new Animation1(this); t1.start(); } public void stop() { if (t != null) { t = null; } if (t1 != null) { t1 = null; } public void paint(Graphics g) { t.draw(g); t1.draw(g); }

Double buffering Prevents flashing when multiple parts are being drawn to the screen Receives all of the updates (from multiple parts) to a window during an update

import java.applet.Applet; import java.awt.*; class Animation extends Thread { private Applet appl; private Color color; private int increment; private int which; private int position = 0; private int pause; Animation(Applet a, Color c, int which, int p, int in) { color = c; appl = a; pause = p; increment = in; this.which = which; } public void run() { Thread thisThread = Thread.currentThread(); while (this == thisThread) { try { Thread.sleep(pause); } catch (InterruptedException e) {} position += increment; if (position > 100 || position < 0) increment = -increment; appl.repaint(); } Double buffering to avoid flickering

public void draw(Graphics g) { g.setColor(color); if (which == 1) g.fillOval(5, 5 + position, 30, 30); else g.fillRect(40 + position, 25, 30, 30); } Double Buffering

public class Anim2b extends Applet { private Animation t, t1; private Image img; // image buffer private Graphics gcopy; // graphics tool for the image buffer public void init() { img = createImage(getWidth(), getHeight()); gcopy = img.getGraphics(); } public void start() { if (t == null) { t = new Animation(this, Color.red, 1, 50, 3); t.start(); } if (t1 == null) { t1 = new Animation(this, Color.blue, 2, 60, 2); t1.start(); } Double Buffering

public void stop() { if (t != null) { t.stop(); t = null; } if (t1 != null) { t1.stop(); t1 = null; } // change update so that it calls paint without clearing surface // the default implementation of update() clears the background public void update(Graphics g) { paint(g); } public void paint(Graphics g) { gcopy.setColor(Color.white); gcopy.fillRect(0, 0, size().width, size().height); // prepare the image buffer t.draw(gcopy); // draw 1st object on the image offscreen buffer t1.draw(gcopy); // draw the 2nd object g.drawImage(img, 0, 0, this); // copy the offscreen buffer to // the applet display } Double Buffering

Image Maps Image map –Specify regions of an image and assign a specific action to each region –Provide an easy way of linking various parts of an image without dividing the image into separate image files Example: Message appears when user moves cursor over various parts of the image

ImageMap.java Lines // ImageMap.java 2 // Demonstrating an image map. 3 4 // Java core packages 5 import java.awt.*; 6 import java.awt.event.*; 7 8 // Java extension packages 9 import javax.swing.*; public class ImageMap extends JApplet { 12 private ImageIcon mapImage; private String captions[] = { "Common Programming Error", 15 "Good Programming Practice", 16 "Graphical User Interface Tip", "Performance Tip", 17 "Portability Tip", "Software Engineering Observation", 18 "Testing and Debugging Tip" }; // set up mouse listeners 21 public void init() 22 { 23 addMouseListener( new MouseAdapter() { // indicate when mouse pointer exits applet area 28 public void mouseExited( MouseEvent event ) 29 { 30 showStatus( "Pointer outside applet" ); 31 } } // end anonymous inner class ); // end addMouseListener method call Add MouseMotionListener for when mouse cursor exits applet area

ImageMap.java (Part 2) Lines Lines addMouseMotionListener( new MouseMotionAdapter() { // determine icon over which mouse appears 42 public void mouseMoved( MouseEvent event ) 43 { 44 showStatus( translateLocation( 45 event.getX(), event.getY() ) ); 46 } } // end anonymous inner class ); // end addMouseMotionListener method call mapImage = new ImageIcon( "icons.png" ); } // end method init // display mapImage 57 public void paint( Graphics g ) 58 { 59 mapImage.paintIcon( this, g, 0, 0 ); 60 } // return tip caption based on mouse coordinates 63 public String translateLocation( int x, int y ) 64 { 65 // if coordinates outside image, return immediately 66 if ( x >= mapImage.getIconWidth() || 67 y >= mapImage.getIconHeight() ) 68 return ""; 69 Add MouseMotionListener for hot areas Test coordinates to determine the icon over which the mouse was positioned

ImageMap.java (Part 3) 70 // determine icon number (0 - 6) 71 int iconWidth = mapImage.getIconWidth() / 7; 72 int iconNumber = x / iconWidth; // return appropriate icon caption 75 return captions[ iconNumber ]; 76 } } // end class ImageMap

ImageMap.java (Part 4) Program Output

ImageMap.java (Part 5) Program Output

Loading and Playing Audio Clips Playing audio clips –Method play of class Applet –Method play of class AudioClip –Java’s sound engine Supports several audio file formats –Sun Audio (.au ) –Windows Wave (.wav ) –Macintosh AIFF (.aif or.aiff ) –Musical Instrument Digital Interface (MIDI) (.mid )

import java.applet.AudioClip; import javax.swing.JApplet; public class AudioExample extends JApplet{ private AudioClip sound; public void init() { sound = getAudioClip( getDocumentBase(), "welcome.wav" ); } public void start() { sound.play(); } A simple Applet example with audio

LoadAudioAndPlay.java Line 13 1 // LoadAudioAndPlay.java 2 // Load an audio clip and play it. 3 4 // Java core packages 5 import java.applet.*; 6 import java.awt.*; 7 import java.awt.event.*; 8 9 // Java extension packages 10 import javax.swing.*; public class LoadAudioAndPlay extends JApplet { 13 private AudioClip sound1, sound2, currentSound; 14 private JButton playSound, loopSound, stopSound; 15 private JComboBox chooseSound; // load the image when the applet begins executing 18 public void init() 19 { 20 Container container = getContentPane(); 21 container.setLayout( new FlowLayout() ); String choices[] = { "Welcome", "Hi" }; 24 chooseSound = new JComboBox( choices ); chooseSound.addItemListener( new ItemListener() { // stop sound and change to sound to user's selection 31 public void itemStateChanged( ItemEvent e ) 32 { 33 currentSound.stop(); 34 Declare three AudioClip objects

LoadAudioAndPlay.java (Part 2) Lines currentSound = 36 chooseSound.getSelectedIndex() == 0 ? 37 sound1 : sound2; 38 } } // end anonymous inner class ); // end addItemListener method call container.add( chooseSound ); // set up button event handler and buttons 47 ButtonHandler handler = new ButtonHandler(); playSound = new JButton( "Play" ); 50 playSound.addActionListener( handler ); 51 container.add( playSound ); loopSound = new JButton( "Loop" ); 54 loopSound.addActionListener( handler ); 55 container.add( loopSound ); stopSound = new JButton( "Stop" ); 58 stopSound.addActionListener( handler ); 59 container.add( stopSound ); // load sounds and set currentSound 62 sound1 = getAudioClip( getDocumentBase(), "welcome.wav" ); 63 sound2 = getAudioClip( getDocumentBase(), "hi.au" ); 64 currentSound = sound1; } // end method init 67 Method getAudioClip loads audio file into AudioClip object

LoadAudioAndPlay.java (Part 3) Line 71 Line 81 Line // stop the sound when the user switches Web pages 69 public void stop() 70 { 71 currentSound.stop(); 72 } // private inner class to handle button events 75 private class ButtonHandler implements ActionListener { // process play, loop and stop button events 78 public void actionPerformed( ActionEvent actionEvent ) 79 { 80 if ( actionEvent.getSource() == playSound ) 81 currentSound.play(); else if ( actionEvent.getSource() == loopSound ) 84 currentSound.loop(); else if ( actionEvent.getSource() == stopSound ) 87 currentSound.stop(); 88 } 89 } } // end class LoadAudioAndPlay Method stop stops playing the audio clip Method play starts playing the audio clip Method loops plays the audio clip continually