Beginning Java 2- JDK 1.3 Version
Images and Animation
Try It Out – Fading an Image
We will fade the Wrox Press logo into the background until it disappears,
and then fade it in again cyclically. We can write an applet to do this and
while we are about it, we can try using parameters for the applet that we
can set in the web page. Here's the code for the applet:
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
public class FaderApplet extends JApplet
{
public void init()
{
// Get parameters - if any
String fade = getParameter("fadeTime");
if(fade != null)
fadeTime = Integer.parseInt(fade);
String fps = getParameter("frameRate");
if(fps != null)
frameRate = Integer.parseInt(fps);
maxCount = frameRate*fadeTime; // Count of steps to complete fade
imagePanel = new ImagePanel(getSize());
getContentPane().add(imagePanel);
composite = AlphaComposite.SrcOver;
}
// Parameter information for anyone that needs it
public String[][] getParameterInfo()
{
String[][] info = {
{"fadeTime" , "integer", "time to complete fade in seconds"},
{"frameRate", "integer", "frames per second"}
};
return info;
}
public void start()
{
timer = new java.util.Timer(true); // Timer to run clock
count = maxCount; // Set repaint counter
alphaStep = 1.0f/count;
long frameInterval = ONE_SECOND/frameRate;
// Use fixed-delay execution to get smooth fade
timer.schedule(new java.util.TimerTask()
{
public void run()
{
imagePanel.repaint(); // Repaint the image
// Update alpha composite for next frame
if(count ==maxCount)
countDelta = -1;
else if(count == 0)
countDelta = 1;
count += countDelta;
composite = AlphaComposite.getInstance(
AlphaComposite.SRC_OVER,count*alphaStep);
}
int countDelta = -1; // Anonymous class member – count incr.
},
0, // ...starting now
frameInterval); // Repaint interval
}
public void stop()
{
timer.cancel();
}
class ImagePanel extends JPanel
{
// Panel creates its own image from an image icon
public ImagePanel(Dimension size)
{
ImageIcon icon = new ImageIcon("Images/wrox_logo.gif");
image = icon.getImage();
// Create a scaled image to fit within the size
image = image.getScaledInstance(4*size.width/5,
4*size.height/5, Image.SCALE_SMOOTH);
// Wait for scaled image to load
MediaTracker tracker = new MediaTracker(this);
tracker.addImage(image,0); // Image to track
try
{
tracker.waitForID(0);
}
catch(InterruptedException e)
{
System.out.println(e); // Exception...
System.exit(1); // ...so abandon ship!
}
}
public void paint(Graphics g)
{
Graphics2D g2D = (Graphics2D)g;
Dimension size = getSize(); // Get panel size
g2D.setPaint(Color.lightGray); // Background color
g2D.fillRect(0,0,size.width,size.height); // fill the panel
g2D.setComposite(composite); // Set current alpha
// Scale and draw image
g2D.drawImage(image, // Image to be drawn
size.width/10,size.height/10, // Image position inset
null);
}
// ImagePanel data members
Image image; // The image
int imageWidth; // and its width
int imageHeight; // and height
}
// Applet data members
final int ONE_SECOND = 1000; // One second in milliseconds
int frameRate = 20; // Default fade change frequency frames per sec
int fadeTime = 3; // Default time to fade completely in seconds
int count; // Repaint cycle counter
int maxCount;
ImagePanel imagePanel; // Panel displaying the image
AlphaComposite composite; // Alpha value for the image
float alphaStep; // Alpha increment for fade step
java.util.Timer timer; // Timer to control fading
}
[Lines 77 and 78 above are one line. They have been split for formatting
purposes.]
We can optionally supply parameters for the applet, so you can use the
following HTML:
<applet code="FaderApplet.class" width="300" height="330">
<param name="frameRate" value="20">
<param name="fadeTime" value="3">
</applet>
You can use appletviewer to run the applet with an HTML file
with the contents above. You should see the image fade out then back in
again.
New on the Java Boutique:
New Review:
Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling
API boasts simplicity, ease-of-integration, a well-rounded feature
set, and it's free!
New Applet:
Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA
sequences into three useful formats.
Elsewhere on internet.com:
WebDeveloper Java
Lots of Java information on webdeveloper.com
WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.
ScriptSearch Java
Hundreds of free Java code files to download.
jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.