![](/img/trans.png)
[英]Attempting to set JLabel icon to image directory, null pointer exception instead
[英]Trying to set image icon for JLabel but URL returns null
尝试为JLabel
设置图像图标,但返回null
URL?
我正在使用Netbeans,并在项目中包含background.png,但它仍返回null
?
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
public class NewClass extends JFrame {
JLabel o = new JLabel();
public NewClass() {
createImage("background.png");
add(o);
setVisible(true);
setSize(100, 100);
setResizable(false);
}
public static void main(String[] args) {
new NewClass();
}
public void createImage(String str) {
URL url = getClass().getResource(str);
try {
BufferedImage image = ImageIO.read(url);
o.setIcon(new ImageIcon(image));
} catch (Exception e) {
e.printStackTrace();
}
}
}
堆栈跟踪中的错误详细信息:
java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1388)
at Test.NewClass.createImage(NewClass.java:32)
at Test.NewClass.<init>(NewClass.java:18)
at Test.NewClass.main(NewClass.java:26)
当我尝试时,请您能不能确定为什么它不起作用
JLabel o = new JLabel(new ImageIcon("background.png");
它可以工作,但是如果background.png不存在,这很容易出错? 谢谢
编辑:components-SplitPaneDemo2Project-这是netbeans项目的名称,背景png直接在此文件夹内
位于此处:C:\\ Users \\ John \\ Documents \\ NetBeansProjects \\ components-SplitPaneDemo2Project
屏幕截图:
我已经对您的代码进行了一些更改测试,并且效果很好:
public class NewClass extends javax.swing.JFrame {
JLabel o = new JLabel();
public NewClass() {
initComponents();
createImage("background.png");
add(o);
setVisible(true);
setSize(100, 100);
setResizable(false);
o.setLocation(20, 20);
o.setSize(100, 25);
}
public void createImage(String str) {
URL url = getClass().getResource(str);
try {
BufferedImage image = ImageIO.read(url);
o.setIcon(new ImageIcon(image));
} catch (Exception e) {
e.printStackTrace();
}
}
....
}
在构造函数中,我已经为“ o”设置了位置和大小。
“ background.png”必须位于“ NewClass”的父包中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.