Chapter 3-Multimedia Programming
Chapter 3-Multimedia Programming
Chapter 3-Multimedia Programming
Chapter 3
Multimedia Programming
Working with 2D Graphics
Java 2D API provides the facilities to draw a wide range of two dimensional geometric
primitives, such as lines, curves, rectangles, and ellipses, as well as a mechanism for ren-
dering virtually any geometric shape. We can use two classes (Graphics and Graphic-
s2D) for this rendering.
x2, y2
Drawing Rectangles
To draw rectangles, we use drawRect method in the Graphics class as shown below:
g.drawRect(x1, y1, w, h);
Note: If we want to draw the square we need to provide the same value for width and
height.
Drawing Filled Rectangles
To draw filled rectangles with colors, we use fillRect method in the Graphics class as
shown below:
g.setColor(Color.red);
g.fillRect(x1, y1, w, h);
In this case red color is filled inside the rectangle as below.
x1, y1
w
Drawing Ovals
To draw an empty oval we use the drawOval method as given below:
g.drawOval(x1, y1, w, h);
Where (x1, y1) = Co-ordinate of to-left point of the enclosing rectangle
w, h = width and height of the enclosing rectangle.
x1, y1
w
This method finds the co-ordinates of middle points of the rectangle and draws the oval
by joining these middle points. The enclosing rectangle is not drawn.
To draw a filled oval we use the fillOval method as shown below:
g.setColor(Color.blue);
g.fillOval(x1, y1, w, h);
x1, y1
w
To draw a circle we provide same value of width and height for the enclosing rectangle,
that is, enclosing rectangle must be a square.
Drawing Arcs
To draw an empty arc we use the drawArc method as given below:
g.drawArc(x, y, w, h, SA, AA);
Where:
x, y = coordinates of top left coordinates of enclosing rectangle
w, h = width and height of enclosing rectangle
SA = starting arc angle
AA = arc angle
g.setColor(Color.blue);
g.fillPolygon(p);
OR
int []x = {10,10,60};
int []y = {0,30,70};
g.setColor(Color.blue);
g.fillPolygon(x,y,3);
If we do not want to connect the start and end point of the polygon we use drawPolyLine
method as follows:
g.drawPolyline(x, y, int n);
Where
x = set of x co-ordinates
y = set of y co-ordinates
n = number of points
For example,
int []x = {10,10,60};
int []y = {10,30,70};
g.drawPolyline(x,y,3);
Clipping an Area
We can restrict the drawing area by using clipping operation. By using clipping we can
view the small areas from the large object. For example we can get half of the oval by
limiting the drawing area. We can clip an area by using following methods:
g.clipRect(x, y, w, h);
g.setClip(x, y, w, h);
These methods intersect the current clip with the specified rectangle. The resulting
clipping area is the intersection of the current clipping area and the specified rectangle.
For example,
g.clipRect(50,75,150,50);
g.fillOval(50,50,150,100);
We can find the clipping bound by using getClipBounds method as below:
Rectangle r = g.getClipBounds( );
Font.PLAIN
Font.BOLD
Font.ITALIC
Font.BOLD + Font.ITALIC
To use a font that you have created, you must select it using setFont
method. Its general form is:
void setFont(Font fontObj)
For example,
Font f = new Font ("Helvetica", Font.BOLD, 44);
setFont(f);
g.drawString("Hello",100,100);
To obtain information about the currently selected font, we use getFont
method. Its general form is:
Font getFont()
In many cases, it is a great convenience because it allows you to specify your shapes in
coordinates that are meaningful to you (such as millimeters or inches) and then translate
to pixels. The designers of the 2D library have supplied two versions of each shape class:
one with float coordinates and one with double coordinates.
Rectangle2D Class
This is an abstract class with two concrete subclasses, which are also static inner classes:
Rectangle2D.Float and Rectangle2D.Double.
The Point2D class is very useful - it is more object-oriented to work with Point2D
objects than with separate x- and y- values. Many constructors and methods accept
Point2D parameters. It is suggested that you use Point2D objects when you can – they
usually make geometric computations easier to understand.
Ellipse2D Class
For drawing the elliptical shapes we need to provide the coordinates of bounding
rectangles. Then Elliptical shapes are drawn by jointing the mid points of the sides of the
rectangle. It is similar to Graphics class. For example,
Ellipse2D e = new Ellipse2D.Double (150, 200, 100, 50);
constructs an ellipse that is bounded by a rectangle with the top-left corner at (150, 200),
Width 100 and height 50.
RoundRectangle2D Class
For drawing the round edges rectangular shapes we need to provide the top left corner,
width and height, and the x- and y-dimension of the corner area that should be rounded.
For example,
RoundRectangle2D r = new RoundRectangle2D.Double(150, 200, 100, 50, 20, 20);
produces a rounded rectangle with circles of radius 20 at each of the corners.
Arc2D Class
To construct an arc, you specify the bounding box, followed by the start angle and the
angle swept out by the arc and the closure type, one of Arc2D.OPEN, Arc2D.PIE, or
Arc2D.CHORD. Its general form is:
Arc2D a = new Arc2D.Double (x, y, width, height, startAngle, arcAngle, closureType);
OR
Arc2D a = new Arc2D.Float (x, y, width, height, startAngle, arcAngle, closureType);
For Example
Arc2D a = new Arc2D.Double(10, 10, 200, 200, 45, 180, Arc2D.CHORD);
QuadCurve2D Class
The Java 2D package supplies quadratic curves. Quadratic curves are specified by two
end points and one control point. Moving the control points changes the shape of the
curves. Its general form is:
QuadCurve2D q = new QuadCurve2D.Double(startX, startY, controlX, controlY, endX,
endY);
For example,
QuadCurve2D q = new QuadCurve2D.Float(10,10,50,300,200,200);
CubicCurve2D Class
The Java 2D package supplies cubic curves. Cubic curves are specified by two end points
and two control point. Moving the control points changes the shape of the curves. Its
We define colors with the Color class. The java.awt.Color class offers predefined
constants for the 13 standard colors listed in following table
Black Green red
Blue lightGray white
Cyan Magenta yellow
darkGray Orange gray
Pink
For example,
Graphics2D g2d=(Graphics2D)g;
g2d.setPaint(Color.red);
GeneralPath path = new GeneralPath();
Rectangle2D r1 = new Rectangle2D.Float (10.0F, 25.0F, 22.5F, 20.0F);
g2d.draw(r1);
We can specify a custom color by creating a Color object by its red, green, and blue
components. Using a scale of 0–255 (that is, one byte) for the redness, blueness, and
greenness, we call the Color constructor like this:
Color(int redness, int greenness, int blueness)
For example,
g.setPaint(new Color(0, 128, 128));
Filling Shapes
You can fill the interiors of closed shapes (such as rectangles or ellipses) with a color.
Simply call fill instead of draw. For example,
Graphics2D g2d = (Graphics2D)g;
g2d.setPaint(Color.red);
Rectangle2D r1 = new Rectangle2D.Float (10.0F, 25.0F, 22.5F, 20.0F);
g2d.fill(r1);
uing in the 1980s with SGI’s (Silicon Graphics, Inc.) OpenGL and on through today with
Microsoft’s Direct3D (part of Microsoft’s DirectX API) and Java 3D.
Java 3D is the extension to Java for displaying three dimensional graphics. Programs
written in Java 3D can be run on several different types of computer and over the inter -
net. Java 3D is a client-side Java application programming interface (API) developed at Sun Mi-
crosystems for rendering interactive 3D graphics using Java. Using Java 3D you will be able to
develop richly interactive 3D applications, ranging from immersive games to scientific visualiza-
tion applications.
The Java 3D API requires that you have the Java 2 Platform, Standard Edition and
either OpenGL or Direct3D installed on your computer – Java 3D uses OpenGL or Direc-
t3D graphics libraries to render 3D scenes. The Java 3D API is not integrated in the core
Java 2 Platform. To use the Java 3D API, you must install the appropriate Java extension
and utility packages. The Java 3D API packages differ slightly depending on which low-
level graphics libraries are installed on your computer. The version of Java 3D packages
you install depends on your operating system and graphics API.
Basic Steps
Basic steps needed to display 3D objects are:
1. Create a virtual universe to contain your scene.
2. Create a data structure to contain a group of objects.
3. Add an object to the group
4. Position the viewer so that they are looking at the object
5. Add the group of objects to the universe
For example, in the program below, Hello3d() constructor contains five lines that perform
each of these steps. The program displays a glowing cube, the viewer is looking directly
at the red face of the cube, so what you actually see is a red square on a black background
import com.sun.j3d.utils.universe.*;
import com.sun.j3d.utils.geometry.*;
import javax.media.j3d.*;
public class Hello3d {
public Hello3d() {
SimpleUniverse universe = new SimpleUniverse();
BranchGroup group = new BranchGroup();
group.addChild(new ColorCube(0.3));
universe.getViewingPlatform().setNominalViewingTransform();
universe.addBranchGraph(group);
}
public static void main( String[] args ) {
new Hello3d();
}
}
Using Light
The way the light falls on an object provides us with the shading that helps us see shapes
in three dimensions. The example below illustrates how to display a ball lit by a red light.
import com.sun.j3d.utils.geometry.*;
import com.sun.j3d.utils.universe.*;
import javax.media.j3d.*;
import javax.vecmath.*;
public class Ball {
public Ball() {
// Create the universe
SimpleUniverse universe = new SimpleUniverse();
// Create a red light that shines for 100m from the origin
Color3f light1Color = new Color3f(1.8f, 0.1f, 0.1f);
BoundingSphere bounds= new BoundingSphere(new
Point3d(0.0,0.0,0.0), 100.0);
Vector3f light1Direction = new Vector3f(4.0f, -7.0f, -12.0f);
DirectionalLight light1 = new DirectionalLight(light1Color,
light1Direction);
light1.setInfluencingBounds(bounds);
group.addChild(light1);
To place your objects in the scene, you start at point (0, 0, 0), and then move the
objects wherever you want. Moving the objects is called a “transformation”, so the
classes you use are: TransformGroup and Transform3D. You add both the object and the
Transform3D to a TransformGroup before adding the TransformGroup to the rest of your
scene. Detail steps are given below:
Step Example
1. Create a transform, a transform group and Transform transform= new
an object Transform3D();
TransformGroup tg = new
TransformGroup();
Cone cone = new Cone(0.5f, 0.5f);
2. Specify a location for the object Vector3f vector = new
Vector3f(-.2f,.1f , -.4f);
3. Set the transform to move (translate) the transform.setTranslation(vector);
object to that location
4. Add the transform to the transform group tg.setTransform(transform);
5. Add the object to the transform group tg.addChild(cone);
For example,
import com.sun.j3d.utils.geometry.*;
import com.sun.j3d.utils.universe.*;
import javax.media.j3d.*;
import javax.vecmath.*;
public class Position {
public Position() {
SimpleUniverse universe = new SimpleUniverse();
universe.getViewingPlatform().setNominalViewingTransform();
universe.addBranchGraph(group);
}
public static void main(String[] args) {
new Position();
}
}
We can also rotate objects using TransformGroup and Transform3D. The example below
demonstrates this concept with ColorCube:
import com.sun.j3d.utils.universe.*;
import com.sun.j3d.utils.geometry.*;
import javax.media.j3d.*;
import javax.vecmath.*;
public class Hello3d {
public Hello3d() {
SimpleUniverse universe = new SimpleUniverse();
group.addChild(objRotate);
universe.getViewingPlatform().setNominalViewingTransform();
universe.addBranchGraph(group);
}
public static void main( String[] args ) {
new Hello3d();
}
}
After instantiating an AudioClip object, you have to load the actual audio file to be
played. This is achieved with the newAudioClip method - a static method of the Applet
class which takes an instance of the URL class that loads the file. For example,
aClip = Applet.newAudioClip(new URL("file:sound.wav"));
In the above example, an audio file named sound.wav is loaded as the audio file to be
played. Once the audio file is uploaded, you can use the methods of the AudioClip
interface to work with it. The AudioClip interface defines three methods: play() (play a
clip from the beginning), stop() (stop playing the clip), and loop () (play the loop
continuously).
A Complete Program
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.net.*;
class AudioFrame extends JFrame implements ActionListener {
private AudioClip bach;
public AudioFrame() {
super("Audio clip example");
JButton play, loop, stop;
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
play = new JButton("Play");
play.addActionListener(this);
add(play);
loop = new JButton("Loop");
loop.addActionListener(this);
add(loop);
stop = new JButton("Stop");
stop.addActionListener(this);
add(stop);
try {
bach = Applet.newAudioClip(new URL("file:misery.mid"));
}
catch (MalformedURLException mfe) {
System.out.println("An error occured, please try again...");
}
setLayout(new FlowLayout());
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand() == "Play") {
bach.play();
}
if (e.getActionCommand() == "Loop") {
bach.loop();
}
if (e.getActionCommand() == "Stop") {
bach.stop();
}
}
}
class Play {
public static void main(String[] args){
AudioFrame AF = new AudioFrame();
}
}
try {
Player mediaPlayer = Manager.createRealizedPlayer(new
URL("file:Bear.mpg"));
Component video = mediaPlayer.getVisualComponent();
Component controls = mediaPlayer.getControlPanelComponent();
if(video != null)
add(video, BorderLayout.CENTER);
if(controls != null)
add(controls, BorderLayout.SOUTH);
mediaPlayer.start();
}catch( NoPlayerException noPlayerException) {
System.err.println( "No media player found");
}catch(CannotRealizeException cannotRealizeException) {
System.err.println( "Could not realize media player");
}catch(IOException iOException) {
System.err.println( "Error reading from the source");
}
pack();
setVisible(true);
}
}
Creating Animations
Many forms of animation are possible in Java. What all of them have in common is that
they create some kind of motion on the screen by drawing successive frames at a rela-
tively high speed. We can use different colors and sound clips during motion.
To update the screen multiple times, you need to create a new Java thread that con-
tains an animation loop. The animation loop is responsible for keeping track of the cur-
rent frame and for requesting periodic screen updates. To implement a thread, you must
either create a subclass of Thread or adhere to the Runnable interface. For example,
import java.awt.*;
import java.applet.*;
public class Animation extends Applet implements Runnable {
private Thread animator;
private static int x = 10;
public void start() {
animator = new Thread(this);
animator.start();
}
public void run() {
while (Thread.currentThread() == animator) {
repaint();
try {
Thread.sleep(100);
}catch (InterruptedException e) {
break;
}
}
}
public void stop() {
animator = null;
}
public void paint(Graphics g) {
g.drawRect(x,10,100,150);
x = x + 10;
}
}