These are older methods.
Image image = Toolkit.getDefaultToolkit().getImage(ImageUrl);
You often need to load an image with a MediaTracker before use.
See api for example usage.
This method is very slow and loads the new image asynchronously
so you need a MediaTracker for it also. The Graphics class has
drawImage methods that will do this much faster.
bgImage.getScaledInstance(x,y,Image.SCALE_FAST);
You need to sleep the execution thread to see anything in an
animation. Bt don't sleep the event dispatch thread or your gui
will freeze. Do the animating on a background thread.
while(true)
{
panel.resize(x++, y++);
panel.repaint();
}
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImageAnimation extends JPanel implements Runnable {
BufferedImage image;
double scale = 1.0;
Thread thread;
boolean animating = false;
boolean increasing = true;
ImageAnimation(BufferedImage image) {
this.image = image;
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
int w = getWidth();
int h = getHeight();
int iw = image.getWidth();
int ih = image.getHeight();
double x = (w - scale*iw)/2;
double y = (h - scale*ih)/2;
AffineTransform at = AffineTransform.getTranslateInstance(x, y);
at.scale(scale, scale);
g2.drawRenderedImage(image, at);
}
public void run() {
while(animating) {
try {
Thread.sleep(50);
} catch(InterruptedException e) {
stop();
}
scale = scale + (increasing ? 0.05 : -0.05);
if(increasing && scale > 2) {
increasing = false;
} else if(!increasing && scale < 1.0) {
increasing = true;
}
repaint();
}
}
private void start() {
if(!animating) {
animating = true;
thread = new Thread(this);
thread.setPriority(Thread.NORM_PRIORITY);
thread.start();
}
}
private void stop() {
animating = false;
if(thread != null)
thread.interrupt();
thread = null;
}
public static void main(String[] args) throws IOException {
String path = "images/cougar.jpg";
BufferedImage image = ImageIO.read(new File(path));
ImageAnimation test = new ImageAnimation(image);
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(test);
f.setSize(500,500);
f.setLocation(200,200);
f.setVisible(true);
test.start();
}
}