java label 设置背景图片问题.无法显示.求解释.代码如下
//在根目录下已经存在图片文件
import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Practice3 extends JFrame implements ItemListener {
private static final long serialVersionUID = 1L;
JLabel label;
JComboBox<String> box;
Icon icon;
JPanel panel = new JPanel();
public Practice3() {
setContentPane(panel);
initComponents();
setSize(600, 600);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private void initComponents() {
icon = new ImageIcon("1.jpg");
label = new JLabel("",icon,JLabel.CENTER);
box = new JComboBox<String>("1.jpg 2.jpg 3.jpg".split(" "));
panel.add(label, BorderLayout.CENTER);
add(box, BorderLayout.NORTH);
box.addItemListener(this);
}
public static void main(String[] args) {
new Practice3();
}
@Override
public void itemStateChanged(ItemEvent e) {
String s = e.getItem().toString();
icon = new ImageIcon(s);
label.setIcon(icon);
}
}
Java
图片
label
Box
------解决方案--------------------自己打断点调试下啊,看下icon是不是null,如果是null的话,就是图片没获取到,路径有问题