JAVA程序中为什么面板上得图片不显示,代码如下
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"