| |
Starting with JDK 1.4, we have an alternative way of obtaining image
files:
The java.imageio.ImageIO class.
This removes the need to use the Toolkit class.
Apparently, it also removes the need to use the MediaTracker class.
package swingExamples;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Insets;
import java.awt.MediaTracker;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
class ImageIODisplayPanel extends JPanel
{
public ImageIODisplayPanel()
{
URL remoteURL = null;
URL localURL = null;
try
{
// Image file from the Internet
remoteURL = new URL("http://members.lycos.co.uk/pinkwall/memor.jpg");
// Image file located relative to the current class file
Class mainClass = ImageIODisplay.class;
localURL = mainClass.getResource("../images/monalisa.jpg");
// Get the images
m_dali = ImageIO.read(remoteURL);
m_davinci = ImageIO.read(localURL);
}
catch (MalformedURLException mue)
{
mue.printStackTrace();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Dimension d = getSize();
Insets in = getInsets();
int clientWidth = d.width - in.right - in.left;
int clientHeight = d.height - in.bottom - in.top;
// Draw Dali's Persistence of Memory
int cx = in.left + 5;
int cy = in.top + 5;
g.drawImage(m_dali, cx, cy, this);
// Draw DaVinci's Mona Lisa
cx += m_dali.getWidth(this) + 5;
g.drawImage(m_davinci, cx, cy, this);
}
private Image m_dali;
private Image m_davinci;
}
class ImageIODisplayFrame extends JFrame
{
public ImageIODisplayFrame()
{
setTitle("ImageIODisplay");
setSize(650, 450);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container contentPane = getContentPane();
contentPane.add( new ImageIODisplayPanel() );
}
}
public class ImageIODisplay
{
public static void main(String[] args)
{
ImageIODisplayFrame frame = new ImageIODisplayFrame();
frame.setVisible(true);
}
}
|
which produces the following:
|