Erro ao amarzenar valor de um campo de texto em um vetor de um objeto, ajuda pf

4 respostas
Djeymisson

Estou desenvolvendo um aplicativo no netbeans para cadastro de aluno, e estou usando as ferramentas do mesmo para fazer uma interface simples, só q precisei criar um vetor do objeto Aluno, só q quando eu tento armazenar uma String q esteja digitada no campo de texto ele exibe o seguinte erro: [color=red]Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException[/color]

obs:sou iniciante em progamação java e talvez eu tenha errado na criação do vetor, outra coisa estou apenas no inicio

esse é o codigo da interface:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package escola.matricula;

import javax.swing.JOptionPane;
/**
 *
 * @author Usuário
 */
public class Matricula extends javax.swing.JFrame {

    Aluno[] novoAluno = new Aluno[10];
    
    public Matricula() {
        initComponents();
    }

    /**
     * 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() {

        rotuloNovoAluno = new javax.swing.JLabel();
        CampoNomeDoaluno = new javax.swing.JTextField();
        RotuloNome = new javax.swing.JLabel();
        BotaoConfirmar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Novo Aluno");

        rotuloNovoAluno.setFont(new java.awt.Font("Comic Sans MS", 1, 24)); // NOI18N
        rotuloNovoAluno.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        rotuloNovoAluno.setText("Novo Aluno");

        RotuloNome.setFont(new java.awt.Font("Comic Sans MS", 0, 11)); // NOI18N
        RotuloNome.setText("Nome:");

        BotaoConfirmar.setText("Confirmar");
        BotaoConfirmar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BotaoConfirmarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(155, 155, 155)
                        .addComponent(rotuloNovoAluno, javax.swing.GroupLayout.DEFAULT_SIZE, 522, Short.MAX_VALUE)
                        .addGap(168, 168, 168))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(RotuloNome, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(CampoNomeDoaluno))))
                .addGap(28, 28, 28))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(BotaoConfirmar)
                .addGap(62, 62, 62))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(rotuloNovoAluno, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(RotuloNome, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(CampoNomeDoaluno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 480, Short.MAX_VALUE)
                .addComponent(BotaoConfirmar)
                .addGap(36, 36, 36))
        );

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

    private void BotaoConfirmarActionPerformed(java.awt.event.ActionEvent evt) {                                               
        novoAluno[1].setNdA(CampoNomeDoaluno.getText());     //O erro ocorre aki<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    }                                              

    /**
     * @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 {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Matricula.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Matricula.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Matricula.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Matricula.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new Matricula().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton BotaoConfirmar;
    private javax.swing.JTextField CampoNomeDoaluno;
    private javax.swing.JLabel RotuloNome;
    private javax.swing.JLabel rotuloNovoAluno;
    // End of variables declaration
}
e esse é o do objeto aluno:
package escola.matricula;

public class Aluno{
    
    private String NomedoAluno,
            DatadeNascimento,
            Sexo,
            Cidade,
            Estado,
            NomedoPai,
            ProPai,
            NomedaMae,
            ProMae,
            Telefone;
    private int Serie,
            CodigodoAluno;
    
    public void setNdA(String NdA){//Set nomedoaluno
        this.NomedoAluno = NdA;
    }
    public String getNdA(){//Get nomedoaluno
        return NomedoAluno;
    }
    public void setDdN(String DdN){//Set datadenascimento
        this.DatadeNascimento = DdN;
    }
    public String getDdN(){//Get DatadeNascimento
        return DatadeNascimento;
    }
    public void setSexo(String Sexo){//Set Sexo
        this.Sexo = Sexo;
    }
    public String getSexo(){//Get Sexo
        return Sexo;
    }
    public void setCidade(String Cidade){//Set Cidade
        this.Cidade = Cidade;
    }
    public String getCidade(){//Get Cidade
        return Cidade;
    }
    public void setEstado(String estado){//Set Estado
        this.Estado = estado;
    }
    public String getEstado(){//Get Estado
        return Estado;
    }
    public void setNdP(String NdP){//Set nomedopai
        this.NomedoPai = NdP;
    }
    public String getNdP(){//Get nomedoPai
        return NomedoPai;
    }
    public void setProP(String ProP){//Set ProfissaoPai
        this.ProPai = ProP;
    }
    public String getProP(){//Get ProfissaoPai
        return ProPai;
    }
    public void setNdM(String NdM){//Set nomedamae
        this.NomedaMae = NdM;
    }
    public String getNdM(){//Get nomedamae
        return NomedaMae;
    }
    public void setProM(String ProM){//Set Profissaodamae
        this.ProMae = ProM;
    }
    public String getProM(){//Get ProfissaodaMae
        return ProMae;
    }
    public void setTelefone(String tel){//Set Profissaodamae
        this.Telefone = tel;
    }
    public String getTelefone(){//Get ProfissaodaMae
        return Telefone;
    }
    public void setCodigo(int Codigo){//Set CodigodoAluno
        this.CodigodoAluno = Codigo;
    }
    public int getCodigo(){//Get CodigodoAluno
        return CodigodoAluno;
    }
    
    
}

quem souber por favor me ajuda, preciso muito terminar esse programa :/

4 Respostas

A

Esse erro ocorre pq vc não atribuiu nenhum objeto na matriz novoAluno.
por isso que qnd vc tenta chama um metodo nessa linha ocorre java.lang.NullPointerException, ou seja a variavel de referencia novoAluno[1] não aponta pra lugar nenhum.

novoAluno[1].setNdA(CampoNomeDoaluno.getText());

Inicialize a matriz com objetos alunos antes de tenta chama alguma metodo com ela.

Djeymisson

Então seria assim?

Aluno[] novoAluno = new Aluno[10]; novoAluno[1] = new Aluno();

pq ele ta dando erro… ele pede pra criar uma classe novoAluno
n to conseguindo inicializar

A

Eu adicionei essa linha e não deu erro nenhum:

private void BotaoConfirmarActionPerformed(java.awt.event.ActionEvent evt) { novoAluno[1] = new Aluno(); novoAluno[1].setNdA(CampoNomeDoaluno.getText()); }

É melhor vc inicializar a matriz novoAluno no construtor:

public Matricula() { initComponents(); for(int x=0;x<novoAluno.length;x++){ novoAluno[x] = new Aluno(); } }

Djeymisson

Oh simmm agora foi… tava inicializando na linha errada… oobrigado aê !!! (y)

Criado 2 de dezembro de 2012
Ultima resposta 3 de dez. de 2012
Respostas 4
Participantes 2