簡體   English   中英

無法加載圖標資源

[英]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_pa​​ckage_name / name,其中Modifyed_pa​​ckage_name是此對象的程序包名稱,用“ /”代替“。”。 ('\\ u002e')。

如果圖像在“ res”文件夾(在項目根目錄下)下,則需要一個斜杠,並且路徑應類似於:

new ImageIcon(getClass().getResource("/res/richard.png"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM