NullPointerException em javax.swing.ImageIcon

21 respostas
netbeansjava
tsartori

Estou com um problema para gerar um .jar no NetBeans 11.

passei o caminho relativo “/br/house/icons/icon32.png”
Quando mando compilar e depois vou executar não abre.
Quando mando executar pelo netbeans me retorna esse erro

Ja troquei pelo caminho completo tb.
“C:/…/br/house/icons/icon32.png”

Sem sucesso

Peguei o .jar compilado e abri com o winrar e nele n consta o caminho “br/house/icons/…”
os demais pacotes estão constando, apenas o pacote dos ícones não.

Exception in thread AWT-EventQueue-0 java.lang.NullPointerException

at javax.swing.ImageIcon.(ImageIcon.java:217)

at br.house.main.mainBotPainel.initComponents(mainBotPainel.java:59)

at br.house.main.mainBotPainel.(mainBotPainel.java:22)

at br.house.main.mainBotPainel.lambda$main$0(mainBotPainel.java:147)

at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)

at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)

at java.awt.EventQueue.access$500(EventQueue.java:97)

at java.awt.EventQueue$3.run(EventQueue.java:709)

at java.awt.EventQueue$3.run(EventQueue.java:703)

at java.security.AccessController.doPrivileged(Native Method)

at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)

at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)

at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)

at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)

at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)

at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

21 Respostas

lvbarbosa

Fica difícil ajudar sem ter contexto. Onde está dando esse erro? Cadê a stack trace? O que você já tentou fazer para resolver o problema? Quanto mais contexto você der, mais fácil fica para alguém te ajudar.

lvbarbosa

Esse caminho existe no sistema? Essa barra no começo do path indica a raiz do sistema, um caminho absoluto. É isso mesmo que você quer?

tsartori

Ja troquei pelo caminho completo tb.
“C:/…/br/house/icons/icon32.png”

Sem sucesso

tsartori

Peguei o .jar compilado e abri com o winrar e nele n consta o caminho “br/house/icons/…”
os demais pacotes estão constando, apenas o pacote dos ícones não.

lvbarbosa

Você precisa configurar a IDE para colocar isso dentro do jar. Por default isso não acontece. A não ser que você coloque os ícones na pasta resources.

tsartori

Como faço isso?

Dentro do meu projeto tenho
Source Packages (br.house.icons // br.house.main // br.house.util)
Dependencies (MySql )
Java Dependencies (java 8)
Project Files (pom.xlm // nbactions.xml)

Jothar_Aleksander

getClass().getResource(“/br/house/icons/icon32.png”); não resolve?

Exemplo:
setIconImage(new ImageIcon(getClass().getResource("/br/house/icons/icon32.png")).getImage());

tsartori

`lbImgFundo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/house/icons/icon32.png")));

É exatamente o que estou fazendo

Jothar_Aleksander

E com o getImage() no final?
Exemplo (que eu uso por aqui):

private void setIcone(){
	setIconImage(new ImageIcon(getClass()
			.getResource("/img/favicon.png")).getImage());
}

Para fins de teste, mande imprimir o caminho, por exemplo:

System.out.println(new ImageIcon(getClass().getResource("/img/favicon.png")));

Já que o o método getResource(String name) retorna:

Um objeto de URL; null se nenhum recurso com esse nome for encontrado, o recurso não pode ser localizado por uma URL, o recurso está em um pacote que não esteja aberto para pelo menos o módulo de chamada ou o acesso ao recurso será negado pelo gerente de segurança.
Throws:
NullPointerException - se o nome for nulo

tsartori

Esse código é gerado automaticamente pelo NetBeans. O engraçado que em outros projetos que tenho aqui funciona perfeitamente.

A unica diferença deste projeto para os demais é a utilização do maven.

staroski

Posta o fonte da classe mainBotPainel.

Só vai indicar a raíz do sistema se estiver utilizando as classes File ou Path.

Se estiver usando o método getResource ou getResourceAsStream da classe Class, então essa / significa que é para buscar a partir da raíz do classpath da aplicação, o que é a forma mais correta.

tsartori
package br.house.main;

import java.awt.Dimension;
import java.awt.Rectangle;

/**
 *
 * @author Thiago Sartori
 * Tel/Whats ([telefone removido]
 */
public class mainBotPainel extends javax.swing.JFrame {

    /**
     * Creates new form mainBotPainel
     */
    public mainBotPainel() {
        initComponents();
        PosicionaJanela();
    }

    private void PosicionaJanela() {
        Dimension objDim = this.getToolkit().getScreenSize();
        Rectangle abounds = this.getBounds();
        this.setLocation((objDim.width - abounds.width) / 2, (objDim.height - abounds.height) / 2);
        this.requestFocus();
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        pnMain = new javax.swing.JPanel();
        lbImgFundo = new javax.swing.JLabel();
        jMenuBar1 = new javax.swing.JMenuBar();
        mnSartoriBot = new javax.swing.JMenu();
        mnOferta = new javax.swing.JMenuItem();
        mnCadastraCliente = new javax.swing.JMenuItem();
        mnEntregas = new javax.swing.JMenuItem();
        mnAjuda = new javax.swing.JMenu();
        mnSobre = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("@Sartori_Bot :: Gerenciador");
        setMinimumSize(new java.awt.Dimension(1280, 742));
        setPreferredSize(new java.awt.Dimension(1280, 742));
        setResizable(false);

        pnMain.setToolTipText("");
        pnMain.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        pnMain.setMinimumSize(new java.awt.Dimension(1280, 742));

        lbImgFundo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/house/icons/telegramWallpaper.jpg"))); // NOI18N
        lbImgFundo.setToolTipText("");
        lbImgFundo.setName(""); // NOI18N

        javax.swing.GroupLayout pnMainLayout = new javax.swing.GroupLayout(pnMain);
        pnMain.setLayout(pnMainLayout);
        pnMainLayout.setHorizontalGroup(
            pnMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(lbImgFundo)
        );
        pnMainLayout.setVerticalGroup(
            pnMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(lbImgFundo)
        );

        mnSartoriBot.setText("Sartori_bot");

        mnOferta.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.CTRL_MASK));
        mnOferta.setText("Criar oferta");
        mnSartoriBot.add(mnOferta);

        mnCadastraCliente.setText("Cadastrar cliente");
        mnSartoriBot.add(mnCadastraCliente);

        mnEntregas.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_E, java.awt.event.InputEvent.CTRL_MASK));
        mnEntregas.setText("Painel de Entregas");
        mnSartoriBot.add(mnEntregas);

        jMenuBar1.add(mnSartoriBot);

        mnAjuda.setText("Ajuda");

        mnSobre.setText("Sobre");
        mnSobre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnSobreActionPerformed(evt);
            }
        });
        mnAjuda.add(mnSobre);

        jMenuBar1.add(mnAjuda);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnMain, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnMain, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>                        

    private void mnSobreActionPerformed(java.awt.event.ActionEvent evt) {                                        
        new Sobre(this, true).setVisible(true);
    }                                       

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
            /*for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }*/
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(mainBotPainel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(() -> {
            new mainBotPainel().setVisible(true);
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JLabel lbImgFundo;
    private javax.swing.JMenu mnAjuda;
    private javax.swing.JMenuItem mnCadastraCliente;
    private javax.swing.JMenuItem mnEntregas;
    private javax.swing.JMenuItem mnOferta;
    private javax.swing.JMenu mnSartoriBot;
    private javax.swing.JMenuItem mnSobre;
    private javax.swing.JPanel pnMain;
    // End of variables declaration                   
}
tsartori

lbImgFundo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/house/icons/telegramWallpaper.jpg")));

O problema esta nessa linha, já troquei por png e jpg para ver se tinha diferença

staroski

O método getResource retorna um objeto do tipo URL.
URL só é válido para apontar caminhos no sistema de arquivos do seu sistema operacional ou então endereços na rede.

Quando você quer ler um recurso que está dentro de um JAR, não adianta utilizar o getResource pois ele vai retornar null.
Neste caso tem que utilizar o getResourceAsStream, para ler a imagem de dentro do JAR.

Exemplo:

InputStream resource = getClass().getResourceAsStream("/br/house/icons/telegramWallpaper.jpg");
Image image = ImageIO.read(resource);
setIcon(new ImageIcon(image));
tsartori
InputStream resource = getClass().getResourceAsStream("/br/house/icons/telegramWallpaper.jpg");
    Image image;
    image=null;
    try{
        image = ImageIO.read(resource);
    }catch(Exception e){
        System.out.println(e.getMessage());
    }
    lbImgFundo.setIcon(new ImageIcon(image));

Me retorna o seguinte erro

input == null!

Exception in thread AWT-EventQueue-0 java.lang.NullPointerException

at javax.swing.ImageIcon.(ImageIcon.java:240)

at br.house.main.mainBotPainel.initComponents(mainBotPainel.java:78)

at br.house.main.mainBotPainel.(mainBotPainel.java:29)

at br.house.main.mainBotPainel.lambda$main$0(mainBotPainel.java:166)

at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)

at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)

at java.awt.EventQueue.access$500(EventQueue.java:97)

at java.awt.EventQueue$3.run(EventQueue.java:709)

at java.awt.EventQueue$3.run(EventQueue.java:703)

at java.security.AccessController.doPrivileged(Native Method)

at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74)

at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)

at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205)

at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)

at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)

at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)

at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
staroski

Então a imagem não está dentro de seu JAR

tsartori

A img está no pacote br.house.icons

Como proceder para add ela no .jar?

tsartori

Quando mando abrir o arquivo .JAR utilizando o WinRAR. Nele não consta o pacote br.house.icons

Pq o java não add esse pacote no .JAR?

staroski

Como você está gerando esse JAR?

tsartori

Pelo próprio NetBeans. (Build with Dependencies)

staroski

Não utilizo NetBeans, mas ele deve ter uma opção para adicionar sua pasta de imagens como um source folder ou resource folder do projeto.

Criado 5 de setembro de 2019
Ultima resposta 6 de set. de 2019
Respostas 21
Participantes 4