javax.swing.ImageIcon is 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.
java.net.URL where = new URL("http://www.yahoo.com/logo.jpeg"); ImageIcon anotherIcon = new ImageIcon(where);
A file name in an ImageIcon constructor specifies the file name relative to the location of the class file. This constructor doesn't return until the ImageIcon is completely loaded.
Warning: Just putting the file name or path in the ImageIcon constructor won't work in general for applets or executable jar files. See discussion of class loader in the NetBeans section below.
ImageIcon myIcon = new ImageIcon("images/myPic.gif");
Warning: Just putting the file name or path in the ImageIcon constructor won't work in general for applets, WebStart applications, and executable jar files. See below.
Let's say you have a directory (cardimages) of images (cardimages/ad.gif, ...), and the program is in a package called cardplayer, and you're trying to load the image within the class Card.
cardplayer
package. Add the directory containing the images (cardimages) to the src/cardplayer directory, so you have src/cardplayer/cardimages/ad.gif, etc. ClassLoader cldr = this.getClass().getClassLoader(); java.net.URL imageURL = cldr.getResource("cardplayer/cardimages/ad.gif"); ImageIcon aceOfDiamonds = new ImageIcon(imageURL);
ImageIcon leftArrow = new ImageIcon("leftarrow.gif"); JButton left = new JButton(leftArrow);
An ImageIcon, img, can be drawn on components (a JComponent or 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();
Image与ImageIcon的联合使用:
ImageIcon imageIcon = new ImageIcon("duke.gif"); // Icon由图片文件形成
Image image = imageIcon.getImage(); // 但这个图片太大不适合做Icon
// 为把它缩小点,先要取出这个Icon的image ,然后缩放到合适的大小
Image smallImage = image.getScaledInstance(30,20,Image.SCALE_FAST);
// 再由修改后的Image来生成合适的Icon
ImageIcon smallIcon = new ImageIcon(smallImage);
// 最后设置它为按钮的图片
JButton iconButton = new JButton(smallIcon);