java.lang.Object --javax.swing.ImageIcon
ImageIcon的结构函数:
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class ImageIconDemo { public static void main(String[] args) { JFrame f = new JFrame("ImageIconDemo"); Container contentPane = f.getContentPane(); Icon icon = new ImageIcon(".\\icons\\visa.gif"); JLabel label = new JLabel(icon, JLabel.CENTER); contentPane.add(label); f.pack(); f.show(); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } }
若您想利用读文件的功能,先将图文件转成byte array,再制作Icon组件,你可以用下面的程序帮你完成:
import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.*; public class ImageIconDemo { public static void main(String[] args) { byte[] image = null; JFrame f = new JFrame("ImageIconDemo"); Container contentPane = f.getContentPane(); /* * 在打开文件读文件的过程中可能会发生IOException,因此在下面的程序中用try与catch将此区段包起来。 */ try { File file = new File(".\\icons\\visa.gif");// 利用文件visa.gif建立一个File组件。 int size = (int) file.length();// 并求出此文件的长度。 FileInputStream in = new FileInputStream(file);// 将文件组件放入FileInputStream中。 image = new byte[size]; in.read(image);// 将数据文件读进byte array中。 } catch (IOException e) { System.err.println("File open falure:" + e.getMessage()); } Icon icon = new ImageIcon(image); JLabel label = new JLabel(icon, JLabel.CENTER); contentPane.add(label); f.pack(); f.show(); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } }
Icon是一个Interface,里面包含3种空的抽象文法,分别是getIconHeight()、getIconWidth()与paintIcon();若你想使用Icon类 来制作Icon,你必须实现(implements)这3个方法,我们直接来看下面这个例子,你就能清楚如何实现Icon界面建立Icon组件了。
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class IconDemo implements Icon { int height = 50; int width = 70; public int getIconHeight() { return height; } public int getIconWidth() { return width; } public void paintIcon(Component c, Graphics g, int x, int y) { g.drawRect(x, y, width, height); g.fillRect(x, y, width, height); g.setColor(Color.blue); } public static void main(String[] args) { JFrame f = new JFrame("IconDemo"); Container contentPane = f.getContentPane(); Icon icon = new IconDemo(); JLabel label = new JLabel(icon, JLabel.CENTER); contentPane.add(label); f.pack(); f.show(); f.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); } }