Using mediatracker to pre-load images
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Main extends JFrame {
Main() {
add(BorderLayout.CENTER, new ImagePanel());
setSize(800, 150);
}
public static void main(String[] args) {
Main jrframe = new Main();
jrframe.setVisible(true);
}
}
class ImagePanel extends JPanel {
String images[] = { "i.png", "j.png" };
Image[] imgs = new Image[images.length];
ImagePanel() {
MediaTracker mt = new MediaTracker(this);
for (int i = 0; i < images.length; i++) {
imgs[i] = Toolkit.getDefaultToolkit().getImage(images[i]);
mt.addImage(imgs[i], i);
}
try {
mt.waitForAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int x = 0;
int y = 0;
for (int i = 0; i < imgs.length; i++) {
g.drawImage(imgs[i], x, y, null);
x += imgs[i].getWidth(null);
}
}
}
Related examples in the same category