public class MyImageIcon extends JFrame {
private static final long serialVersionUID = 1L;
public MyImageIcon() {
Container container = getContentPane();// 创建一个标签
JLabel jl = new JLabel("这是一个JFrame窗体", JLabel.CENTER);
// 获取图片URL
URL url = MyImageIcon.class.getResource("imageButton.jpg");
Icon icon = new ImageIcon(url); // 实例化Icon
jl.setIcon(icon); // 为标签设置图片
// 设置文字居中
jl.setHorizontalAlignment(SwingConstants.CENTER);
jl.setOpaque(true);
container.add(jl);
setSize(250, 100);
setVisible(true);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new MyImageIcon();
}
}
出错的提示
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at MyImageIcon.<init>(MyImageIcon.java:21)
at MyImageIcon.main(MyImageIcon.java:34)
图片放在src下了.
21行对应的是
Icon icon = new ImageIcon(url);
34行
new MyImageIcon();