我設置了一個簡單的圖形用戶界面,我試圖加載一個按鈕的圖像卡住了。無法加載圖標的資源
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();
}
}
這是一個簡單的messanging應用程序的客戶端,但我無法讓圖像顯示在按鈕上。我使用getResource()
而不是ImageIcon構造函數,因爲如果我使用它,它不會顯示在Jar中。 那麼我在做什麼錯?無論我如何編寫URL,它都會給我一個NullPointerException。該圖像是在我的項目是「資源」文件夾下..
這是堆棧跟蹤:
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文件。 – romfret
要使用資源,必須使用資源相對於類文件的路徑。請告訴我們這個。 –
我嘗試了一切,/res/richard.png,res/richard.png,richard.png ... 該圖像位於項目根文件夾中的res文件夾中。不知道該怎麼做,或者我我做錯了 – Luca