我想在JLabel中加载一个图片,我写的代码如下,但是不能加载成功。问题在那呢?应该怎样做呢!谢谢!
import javax.swing.*;
import java.awt.*;public class image { /**
 * @param args
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame = new JFrame("Can I add a image to the JLabel?");


Icon icon = new ImageIcon("C:\\Documents and Settings\\wcw\\My Documents\\My Pictures\\jp.gif");
//JLabel label = new JLabel(icon);
JLabel label = new JLabel();
label.setIcon(icon);
label.setBounds(0, 0, 80, 80);
frame.getContentPane().add(label);
frame.getContentPane().setBackground(Color.blue);

frame.setSize(icon.getIconWidth(),icon.getIconHeight());

frame.setMinimumSize(new Dimension(500,500));
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); }}

解决方案 »

  1.   

    是路径问题,把
    Icon icon = new ImageIcon("C:\\Documents and Settings\\wcw\\My Documents\\My Pictures\\jp.gif");
    写成
    Icon icon = new ImageIcon("C:\\jp.gif");
    就可以了
    当然要把jp.gif拷贝到c:盘下
      

  2.   

    我试了一下,好像不行啊!再说为什莫非要把路径写成 C:\\jp.gif  呢?
    请指教!
      

  3.   

    label.setIcon(new ImageIcon("C:\\Documents and Settings\\wcw\\My Documents\\My Pictures\\jp.gif");是这样的!
    试试,一定能成功!
      

  4.   

    你把你对的给注释掉了!
    路径打反斜杠“\”是一样地!呵呵!
    给你你要的答案!
    刚刚搞出来的!
    代码是你自己打的吧!不然窗口怎么显示在左上脚?
    直接拖就可以,免得错!绝对正确!
    呵呵!package no10;import javax.swing.AbstractAction;
    import javax.swing.JFrame;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JLabel;
    import java.awt.Color;
    import java.awt.Dimension;/**
     * <p>Title: </p>
     *
     * <p>Description: </p>
     *
     * <p>Copyright: Copyright (c) 2007</p>
     *
     * <p>Company: </p>
     *
     * @author not attributable
     * @version 1.0
     */
    public class Untitled1 {
    //import AbstractAction.*;
    //import java.awt.*;    public Untitled1() {
        }
        /**
         * @param args
         */
        public static void main(String[] args) {
    // TODO Auto-generated method stub
            JFrame frame = new JFrame("Can I add a image to the JLabel?");        Icon icon = new ImageIcon(
                    "D:\\No10\\1.jpg");
    //JLabel label = new JLabel(icon);
            JLabel label = new JLabel();
            label.setIcon(icon);
            label.setBounds(0, 0, 80, 80);
            frame.getContentPane().add(label);
            frame.getContentPane().setBackground(Color.red);        frame.setSize(icon.getIconWidth(), icon.getIconHeight());        frame.setMinimumSize(new Dimension(500, 500));
            frame.pack();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);    }
    }