图片路径问题:Swing--ImageIcon(url)
作者:互联网
图片路径问题:Swing–ImageIcon(url)
源代码:
import javax.swing.*;
import java.awt.*;
import java.net.URL;
public class ImageDemo1 extends JFrame {
public ImageDemo1(){
JLabel label = new JLabel("小事情");
//获取图片的地址
URL url = ImageDemo1.class.getResource("ye.jpg");
ImageIcon imageIcon = new ImageIcon(url);
label.setIcon(imageIcon);
label.setHorizontalAlignment(SwingConstants.CENTER);
Container container = getContentPane();
container.add(label);
setVisible(true);
setBounds(100,100,500,400);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new ImageDemo1();
}
}
报错:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:217)
at com.ggl.lesson04.ImageDemo1.<init>(ImageDemo1.java:16)
at com.ggl.lesson04.ImageDemo1.main(ImageDemo1.java:29)
Process finished with exit code 1
报错原因:
//获取图片的地址
URL url = ImageDemo1.class.getResource("ye.jpg");
ImageIcon imageIcon = new ImageIcon(url);
//路径为null,空指针异常
//可以进行如下修改:
ImageIcon imageIcon = new ImageIcon("src/com/ggl/lesson04/ye.jpg");
修改后的代码:
import javax.swing.*;
import java.awt.*;
public class ImageDemo1 extends JFrame {
public ImageDemo1(){
JLabel label = new JLabel("小事情");
//获取图片的地址
ImageIcon imageIcon = new ImageIcon("src/com/ggl/lesson04/ye.jpg");
label.setIcon(imageIcon);
label.setHorizontalAlignment(SwingConstants.CENTER);
Container container = getContentPane();
container.add(label);
setVisible(true);
setBounds(100,100,700,600);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new ImageDemo1();
}
}
运行效果:
标签:ImageIcon,java,ImageDemo1,--,label,url,new,public 来源: https://blog.csdn.net/qq_44758663/article/details/117879982