[英]Can't load resource for Icon
我正在设置一个简单的GUI,但在尝试为按钮加载图像时遇到了麻烦。
public class Client extends JFrame{
private JTextField field;
private JLabel label;
private JButton send;
private Socket socket;
Client(){
super("Messenger");
try {
socket=new Socket("localhost",65535);
} catch (IOException e1) {
System.out.println("can't estabilish connection");
return;
}
setLayout(new FlowLayout());
label=new JLabel("insert text here");
add(label);
field=new JTextField(20);
add(field);
ImageIcon ico=new ImageIcon(getClass().getResource("res/richard.png"));
send=new JButton("send",ico);
send.setFocusPainted(false);
add(send);
send.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Thread(new Runnable() {
public void run() {
try {
OutputStream out=socket.getOutputStream();
String s=field.getText();
if (s.equals(".")) {
out.write(s.getBytes());
socket.close();
System.exit(0);
}
out.write((s+"\n").getBytes());
field.setText("");
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
});
pack();
setLocation(500, 400);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new Client();
}
}
这是一个简单的客户端应用程序,但是我无法将图像显示在按钮上。 我使用的是getResource()
而不是ImageIcon构造函数,因为如果使用它,它就不会显示在Jar中。 那我在做什么错? 无论我如何编写URL,它都会为我提供NullPointerException。 该图像位于我的项目中的“ res”文件夹下。
这是堆栈跟踪:
Exception in thread "main" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(Unknown Source)
at Client.<init>(Client.java:27)
at Client.main(Client.java:58)
它起源于(如预期的)ImageIcon构造函数。
从java.lang.Class#getResource API文档中:
使用以下算法从给定资源名称构造绝对资源名称:
如果名称以'/' ('\\ u002f')开头,则资源的绝对名称是名称中'/'之后的部分。 否则 ,绝对名称的格式如下: modified_package_name / name,其中Modifyed_package_name是此对象的程序包名称,用“ /”代替“。”。 ('\\ u002e')。
如果图像在“ res”文件夹(在项目根目录下)下,则需要一个斜杠,并且路径应类似于:
new ImageIcon(getClass().getResource("/res/richard.png"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.