Java.lang.NullPointerException após separar código

6 respostas
Giacaboy

Eu tinha criado a interface de um programa em um unico arquivo .java. Resolvi separar cada componente da interface em seu próprio arquivo .java. Após fazer isso, começou a dar erro java.lang.NullPointerException. Abaixo estão as partes dos codigos envolvidos e o erro. Se alguém puder me ajudar a entender o q tá acontecendo. Obrigado.

Pedaço do código da classe InterfacePartitura. Ela têm duas classes internas. Ela cria um botão de fechar nas abas. Só omiti o construtor e uma outra função sem importancia para o problema:
private class Aba extends JPanel
    {
        private InterfacePartitura painelAbas;

        public Aba(String titulo, String autor, InterfacePartitura painel)
        {
            this.painelAbas = painel;

            this.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
            this.setBorder(BorderFactory.createEmptyBorder(2,0,0,-2));
            this.setOpaque(false);

            JLabel label = new JLabel(titulo + " - " + autor);
            label.setBorder(BorderFactory.createEmptyBorder(0,0,0,5));

            BotaoAba botao_fechar = new BotaoAba();

            this.add(label);
            this.add(botao_fechar);
        }

        private class BotaoAba extends JButton implements ActionListener
        {
            public BotaoAba()
            {
                this.setPreferredSize(new Dimension(17,17));
                this.setToolTipText("Fechar aba");
                this.setUI(new BasicButtonUI());
                this.setContentAreaFilled(false);
                this.setFocusable(false);
                this.setBorder(BorderFactory.createEtchedBorder());
                this.setBorderPainted(false);
                this.setRolloverEnabled(true);
                this.addMouseListener(buttonMouseListener);
                this.addActionListener(this);
            }

            public void actionPerformed(ActionEvent evento)
            {
                int i = painelAbas.indexOfTabComponent(Aba.this);
                fechaPartitura(i);
            }

            protected void paintComponent(Graphics g)
            {
                super.paintComponent(g);
                Graphics2D g2 = (Graphics2D) g.create();
                //shift the image for pressed buttons
                if (getModel().isPressed()) g2.translate(1, 1);
                g2.setStroke(new BasicStroke(2));
                g2.setColor(Color.BLACK);
                if (getModel().isRollover()) g2.setColor(Color.MAGENTA);
                int delta = 6;
                g2.drawLine(delta, delta, getWidth() - delta - 1, getHeight() - delta - 1);
                g2.drawLine(getWidth() - delta - 1, delta, delta, getHeight() - delta - 1);
                g2.dispose();
            }
        }

        private final MouseListener buttonMouseListener = new MouseAdapter()
        {
            public void mouseEntered(MouseEvent e)
            {
                Component component = e.getComponent();
                if (component instanceof AbstractButton)
                {
                    AbstractButton button = (AbstractButton) component;
                    button.setBorderPainted(true);
                }
            }

            public void mouseExited(MouseEvent e)
            {
                Component component = e.getComponent();
                if (component instanceof AbstractButton)
                {
                    AbstractButton button = (AbstractButton) component;
                    button.setBorderPainted(false);
                }
            }
        };
    }

    public int criaAba(String titulo, String autor, JTextArea area)
    {
        this.addTab(titulo + " - " + autor,area);
        
        Aba novaAba = new Aba(titulo,autor,this);

        this.setTabComponentAt(this.getSelectedIndex(),novaAba);
        this.setSelectedIndex(this.getTabCount() - 1);

        return this.getSelectedIndex();
    }
Função onde dá o problema. Ela está na classe InterfaceIcones que fica em outro arquivo .java. Lembrando que painel_partitura é um objeto do tipo InterfacePartitura e ele foi inicializado no construtor da classe InterfaceIcones:
public void criaPartitura(String titulo, String autor, String clave, int tempo_compasso, int divisao_semibreve, String tom, int bpm, String comentarios)
    {
        JTextArea area = new JTextArea();
        
        int i = this.painel_partitura.criaAba(titulo,autor,area);

        Partitura part = new Partitura(titulo,autor,clave,tempo_compasso,divisao_semibreve,tom,bpm,comentarios);
        this.vetorPartituras.add(i,part);

        //Mostrar conteudo da partitura
        area.setText(titulo);
        area.append("\n" + autor);
        area.append("\n" + clave);
        area.append("\n" + tempo_compasso);
        area.append("\n" + divisao_semibreve);
        area.append("\n" + tom);
        area.append("\n" + bpm);
        area.append("\n" + comentarios);
    }

Erro que tá dando:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at projeto.InterfaceIcones.criaPartitura(InterfaceIcones.java:94)
at projeto.InterfacePegaDados.pegaDados(InterfacePegaDados.java:222)
at projeto.InterfacePegaDados.actionPerformed(InterfacePegaDados.java:125)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6263)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6028)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4574)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.Window.dispatchEventImpl(Window.java:2475)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

Observações:
at projeto.InterfaceIcones.criaPartitura(InterfaceIcones.java:94) é justamente a linha int i = this.painel_partitura.criaAba(titulo,autor,area);
[b]at projeto.InterfacePegaDados.pegaDados(InterfacePegaDados.java:222)
está aparecendo também justamente por usar a função q está dando problema

6 Respostas

Giacaboy

ninguém? =/

eliangela

seguinte… manda o fonte todo pra eu poder rodar aqui…
mas provavelmente é porque vc está passando algum objeto null, ou seja, sem instanciar.
Verifica se vc está instanciando os atributos declarados no corpo da classe

lina

Oi,

A variavel this.painel_partitura foi instanciada? (já foi criada?) se sim, post o código da função criaAba();

Tchauzin!

Giacaboy

eliangela:
seguinte… manda o fonte todo pra eu poder rodar aqui…
mas provavelmente é porque vc está passando algum objeto null, ou seja, sem instanciar.
Verifica se vc está instanciando os atributos declarados no corpo da classe

já revisei td… aparentemente tá td certo…

tae o código. valeu

eliangela

seguinte:
achei o erro:

na classe Interface.java tem essa parte:

this.painel_menu = new InterfaceMenu(this, this.painel_icones, this.painel_partitura, this.painel_propriedades_iniciais, this.vetorPartituras); this.painel_icones = new InterfaceIcones(this.largura, this.altura, this, this.painel_partitura, this.vetorPartituras); this.painel_anexo = new InterfaceAnexo(this.largura, this.altura, this); this.painel_partitura = new InterfacePartitura(this.largura, this.altura, this.vetorPartituras); this.painel_icones_edicao = new InterfaceIconesEdicao(this.largura, this.altura); this.painel_player = new InterfacePlayer(this.largura, this.altura); this.painel_figuras_musicais = new InterfaceFigurasMusicais(this.largura, this.altura); this.painel_teclado_virtual = new InterfaceTecladoVirtual(this.largura, this.altura, this);

os parâmetros que vc está passando pra esses construtores estão nulos.
aonde vc está fazendo this.painel_partitura = new …, coloca ele primeiro que as outras inicializações, já que vc usa o painel_partitura como parametro em quase todos as inicializações…

Mas basicamente seus erros estão partindo daí…

Espero ter ajudado!
Fique com Deus

Giacaboy

eliangela:
seguinte:
achei o erro:

na classe Interface.java tem essa parte:

this.painel_menu = new InterfaceMenu(this, this.painel_icones, this.painel_partitura, this.painel_propriedades_iniciais, this.vetorPartituras); this.painel_icones = new InterfaceIcones(this.largura, this.altura, this, this.painel_partitura, this.vetorPartituras); this.painel_anexo = new InterfaceAnexo(this.largura, this.altura, this); this.painel_partitura = new InterfacePartitura(this.largura, this.altura, this.vetorPartituras); this.painel_icones_edicao = new InterfaceIconesEdicao(this.largura, this.altura); this.painel_player = new InterfacePlayer(this.largura, this.altura); this.painel_figuras_musicais = new InterfaceFigurasMusicais(this.largura, this.altura); this.painel_teclado_virtual = new InterfaceTecladoVirtual(this.largura, this.altura, this);

os parâmetros que vc está passando pra esses construtores estão nulos.
aonde vc está fazendo this.painel_partitura = new …, coloca ele primeiro que as outras inicializações, já que vc usa o painel_partitura como parametro em quase todos as inicializações…

Mas basicamente seus erros estão partindo daí…

Espero ter ajudado!
Fique com Deus

nossa, é claro. tô até com vergonha de num ter percebido isso… nossa… mt obrigado

Criado 3 de setembro de 2009
Ultima resposta 6 de set. de 2009
Respostas 6
Participantes 3