ImageIcon是Icon接口的一個實現類。
ImageIcon類的構造函數:
- ImageIcon()
- ImageIcon(String filename) //本地圖片文件
- ImageIcon(URL location) //網絡圖片
- ImageIcon(byte[] imageData)
- ImageIcon(Image image) //Image是一個抽象類
ImageIcon類的常用方法:
- setImage(Image image)
- getImage() //返回值是Image類型
ImageIcon實現的是
1、設置JLabe、JButton的圖標
1 ImageIcon imageIcon=new ImageIcon("./image/1.png"); 2 3 JLabel label1=new JLabel(imageIcon); 4 JLabel label2=new JLabel("test",imageIcon,SwingConstants.CENTER); 5 6 JButton button1=new JButton(imageIcon); 7 JButton button2=new JButton("提交",imageIcon);
./表示項目的根目錄。
2、設置程序左上角的圖標
1 ImageIcon imageIcon=new ImageIcon("./image/1.png"); 2 frame.setIconImage(imageIcon.getImage()); 3 4 /* 5 參數是Image抽象類的對象。ImageIcon實現的是Icon接口 ,並沒有實現Image抽象類。 6 需要使用getImage()獲取Image對象 7 */
JFrame、JDialog均可使用此種方式設置窗口左上角的圖標。
此圖標就是程序在任務欄顯示的圖標。