Use javax.swing.ImageIcon is commonly used for images, both to use on buttons and labels, and to draw in a graphics panel. The supported formats are .gif, .jpg, and .png.
A filename in an ImageIcon constructor specifies the filename relative to the location of the class file [not always true. See TODO note below]. This constructor doesn't return until the ImageIcon is completely loaded.
ImageIcon myIcon = new ImageIcon("images/myPic.gif");
Note: Java may not always use the current directory of the executing program to make relative file references. A simple, but completely non-portable fix, is to give the entire file path. The better solution, calling getResource() should be used, but it isn't described here yet.
[TODO: The correct solution, compatible with executable jar files, applets, and Web Start, packages, etc, is to use MyClass.class.getResource(relativePath). This works in most (all?) combinations as of Java 1.4. The Java Tutorial has a description of this at http://java.sun.com/docs/books/tutorial/uiswing/misc/icon.html#getresource]
URL where = new URL("http://www.yahoo.com/logo.jpeg");
ImageIcon anotherIcon = new ImageIcon(where);
ImageIcon leftArrow = new ImageIcon("leftarrow.gif");
JButton left = new JButton(leftArrow);
An ImageIcon, img, can be drawn on components (usually a JPanel) using
img.paintIcon(Component c, Graphics g, int x, int y);
Display the image on
a subclass of JPanel used for graphics. Put the paintIcon
call in the paintComponent method of that panel.
To paint the ImageIcon img on the current panel
(ie, this), use a call like:
public void paintComponent(Graphics g) {
super.paintComponent(g);
img.paintIcon(this, g, 100, 100);
}
You can find the width and height of an image with
int w = img.getIconWidth(); int h = img.getIconHeight();