【发布时间】:2015-08-08 08:28:56
【问题描述】:
我正在设置一个简单的 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 构造函数..
【问题讨论】:
-
尝试删除
res/。例如,要确定图像的位置,请使用 7Zip 打开 .jar 文件。 -
要使用资源,你必须使用资源相对于类文件的路径。请告知我们。
-
我什么都试过了,/res/richard.png, res/richard.png,richard.png...图片在项目根文件夹的res文件夹里..不知道是什么做什么,或者我做错了什么
-
根文件夹在这里可能不起作用。移动该文件夹,使其成为类目录的子目录。如果您使用的是 Eclipse,请拖放 res 文件夹,使其成为您的类路径的一个分支。
-
@HovercraftFullOfEels 是的!那钉了它!但为什么会这样?我在错综复杂的文件路径中找不到出路...
标签: java image icons jbutton getresource