import javax.swing.Icon;

import javax.swing.ImageIcon;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JPanel;

import javax.swing.UIManager;

public class IconFame extends JFrame{

JButton load, save, subscribe, unsubscribe;

public IconFame(){

super("Frame Title");

//setSize(300,200);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

JPanel jp = new JPanel();

Icon loadIcon = new ImageIcon("Image/7.gif");

load = new JButton("load",loadIcon); 

jp.add(load);

this.add(jp);

pack();

this.setEnabled(true);

setVisible(true);

System.out.println(this.getSize());

System.out.println(load.getSize());

          

           System.out.println(loadIcon.getIconWidth());

System.out.println(loadIcon.getIconHeight());

}

public static void main(String[] args) {

try {

UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");

} catch (Exception e) {

e.printStackTrace();

IconFame icon = new IconFame();

}

}

  1. 图片7.gif位于D:\JavaProject\Swing\src\Image\7.gif,本以为上面

    Icon loadIcon = new  ImageIcon("Image/7.gif");能把图片加入对象loadIcon中,可用

  System.out.println(loadIcon.getIconWidth());

  System.out.println(loadIcon.getIconHeight());

  显示出来的值为-1,证明没有加入图片。

2.尝试通过Icon loadIcon = new ImageIcon("D:\JavaProject\Swing\src\Image\7.gif");仍然打印    出-1。

3.Icon loadIcon = new ImageIcon("D:\\JavaProject\\Swing\\src\\Image\\7.gif");可正确加入对象  中。