JAVA程序中为什么面板上得图片不显示,代码如下

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

class IconLabelButton extends JFrame implements ActionListener{
JLabel j1;
IconLabelButton(){
JPanel jp=new JPanel();
JButton jb=new JButton("Change");
Icon icon=new ImageIcon("2.bmp");
j1=new JLabel("小猫",icon,SwingConstants.TRAILING);
jp.add(jb);
jp.add(j1);
add(jp);
jb.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
Icon icon=new ImageIcon("1.bmp");
j1.setIcon(icon);
j1.setText("QQ");
}
}

public class Example10_1 {

public static void main(String[] args) {
IconLabelButton f=new IconLabelButton();
f.setTitle("图标标签");
f.setSize(500, 500);
f.setLocation(400, 300);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);

}

}

你可以看一下官方的例子:How to Use Icons

http://docs.oracle.com/javase/tutorial/uiswing/components/icon.html#eg

java里的资源都是需要加载才能看见的,官方的做法通常类似于:

ImageIcon icon = createImageIcon("cat.png",

        "a pretty but meaningless splat");

这里的createImageIcon就是一个预加载的过程

/** Returns an ImageIcon, or null if the path was invalid. */

protected ImageIcon createImageIcon(String path,

                                           String description) {

    java.net.URL imgURL = getClass().getResource(path);

    if (imgURL != null) {

        return new ImageIcon(imgURL, description);

    } else {

        System.err.println("Couldn't find file: " + path);

        return null;

    }

通常这样就会有图像出来了,不过也有可能不出来,这是因为你的图像可能不严格,你可以使用官方例子里面的图片来实验一下,像这个"images/middle.gif"

温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-12-28
按你的代码是可以呈现的!你最好确定下图片的路径是否正确
如:
在显示前用new File("1.bmp").exists()来判断下文件是否存在

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网