Erro ao conectar no banco de dados

0 respostas
G

Olá! Fiz um programa em Java no NetBeans para receber os dados e as notas de alunos. Inicialmente o objeto aluno era inserido em um ArrayList, até aí tudo bem. Em seguida eu modifiquei o código para que os alunos fossem inseridos no banco de dados, pelo método que criei.
Estou usando fazendo o programa de acordo com o exemplo que tenho na apostila da faculdade. O problema é que quando eu vou confirmar a inserção do aluno no bando de dados aparece uma mensagem com o seguinte erro: "error loading driver.java.sql.SQLNon Transient Connection: java.net.ConnectException: Erro ao conectar no servidor 'localhost' porta '1527'. Recebida a mensagem: 'Connection refused: connect' " ...Tem outro problema também: Antes de modificar o código, o aluno era inserido e em seguida, após fechar a tela, era aberta outra tela com os alunos inseridos e a média final de cada aluno. Agora essa segunda janela também não é aberta mais.
Se alguém puder me ajudar...Desde já, muito obrigada!

Segue o código:
Meu código tem 3 classes...
Aluno:

/* 
     * To change this license header, choose License Headers in Project Properties. 
     * To change this template file, choose Tools | Templates 
     * and open the template in the editor. 
     */  
      
    package pacoteInterface;  
      
      
    /** 
     * 
     * @author Giseli 
     */  
    public class Aluno {  
         private String nome;   
         private String matricula;  
         private double prova1;  
         private double prova2;  
         private double trabalhos;  
         private double provafinal;  
      
        Aluno(String n, String m, double p1, double p2, double t){   
            this.nome = n;  
            this.matricula = m;  
            this.prova1 = p1;  
            this.prova2 = p2;  
            this.trabalhos = t;  
            this.provafinal = 0; //Inicializando a nota com zero.  
        }  
      
        Aluno(String nome, String matricula, double nota1, double nota2, double nota3, double provafinal) {  
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.  
        }  
          
       double media() {   
            double m = this.getProva1() +  
                     this.getProva2() +  
                    this.getTrabalhos();  
            if (m < 60){  
                m = (40*m + 60*this.getProvaFinal())/100;  
            }  
            return m;  
              
        }  
          
          
          
        /** 
         * @return the nome 
         */  
        public String getNome() {  
            return nome;  
        }  
      
        /** 
         * @param nome the nome to set 
         */  
        public void setNome(String nome) {  
            this.nome = nome;  
        }  
      
        /** 
         * @return the matricula 
         */  
        public String getMatricula() {  
            return matricula;  
        }  
      
        /** 
         * @param matricula the matricula to set 
         */  
        public void setMatricula(String matricula) {  
            this.matricula = matricula;  
        }  
      
        /** 
         * @return the prova1 
         */  
        public double getProva1() {  
            return prova1;  
        }  
      
        /** 
         * @param prova1 the prova1 to set 
         */  
        public void setProva1(double prova1) {  
            this.prova1 = prova1;  
        }  
      
        /** 
         * @return the prova2 
         */  
        public double getProva2() {  
            return prova2;  
        }  
      
        /** 
         * @param prova2 the prova2 to set 
         */  
        public void setProva2(double prova2) {  
            this.prova2 = prova2;  
        }  
      
        /** 
         * @return the trabalhos 
         */  
        public double getTrabalhos() {  
            return trabalhos;  
        }  
      
        /** 
         * @param trabalhos the trabalhos to set 
         */  
        public void setTrabalhos(double trabalhos) {  
            this.trabalhos = trabalhos;  
        }  
      
        /** 
         * @return the provaFinal 
         */  
        public double getProvaFinal() {  
            return provafinal;  
        }  
      
        /** 
         * @param provaFinal the provaFinal to set 
         */  
        public void setProvaFinal(double provaFinal) {  
            this.provafinal = provaFinal;  
        }  
          
    }
ListaAlunos:
/* 
     * To change this license header, choose License Headers in Project Properties. 
     * To change this template file, choose Tools | Templates 
     * and open the template in the editor. 
     */  
      
    package pacoteInterface;  
      
    import java.sql.Connection;  
    import java.sql.DriverManager;  
    import java.sql.ResultSet;  
    import java.sql.SQLException;  
    import java.sql.Statement;  
    import java.util.ArrayList;  
      
    /** 
     * 
     * @author Giseli 
     */  
    public class ListaAlunos extends javax.swing.JFrame {  
      
        /** 
         * Creates new form ListaAlunoss 
         */  
       // public ListaAlunos() {   
    //ERA ASSIM:   
    public ListaAlunos( ) {  
          
            initComponents();  
            this.alunos = alunos; //Inicializando o objeto alunos //ANTES ERA SSIM  
             //alunos = consultarAlunosBD(); //Inicializando o objeto alunos  
             for (Aluno a: alunos) {  
                this.jComboBox1.addItem(a.getNome());  
            }  
        }  
      
        ArrayList<Aluno> alunos; //DEVE MUDAR DE LUGAR  
      
         
          
          
          
        private void consultarAlunosBD(){  
            String driver = "org.apache.derby.jdbc.ClientDriver";  
            String url = "jdbc:derby://localhost:1527/LP";  
            String username = "giseli";  
            String password = "giseli";  
              
            //Criando um ArrayList para armazenar os dados:  
            ArrayList<Aluno> alunosBD = new ArrayList<Aluno>();  
             try{  
                 Class.forName(driver);  
                 Connection connection = DriverManager.getConnection(  
                                         url, username, password);  
                 Statement statement = connection.createStatement();  
                   
                 String consulta = "SELECT * FROM Aluno";  
                 statement.executeQuery(consulta);  
                   
                 ResultSet results = statement.executeQuery(consulta);  
                 while (results.next()){  
                       
                     String nome = results.getString("nome");  
                     String matricula = results.getString("matricula");  
                       
                    double nota1 = results.getDouble("nota1");  
                    double nota2 = results.getDouble("nota2");  
                    double nota3 = results.getDouble("nota3");  
                    double provafinal = results.getDouble("provafinal");  
                      
                    Aluno a = new Aluno(nome, matricula,  
                               nota1, nota2, nota3, provafinal);  
                    alunosBD.add(a);  
                 }  
                 connection.close();  
             }catch(ClassNotFoundException cnfe){  
                 Interface.mensagemErro("Error loading driver: " + cnfe, "ERRO");  
             }catch(SQLException sqle){  
                 Interface.mensagemErro("Error loading driver: " + sqle, "ERRO");  
             }  
              
              
      
        }  
          
          
          
          
          
          
          
           
          
          
          
          
      
        /** 
         * 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() {  
      
            jLabel1 = new javax.swing.JLabel();  
            jComboBox1 = new javax.swing.JComboBox();  
            jLabel2 = new javax.swing.JLabel();  
            jTextField1 = new javax.swing.JTextField();  
            jButton1 = new javax.swing.JButton();  
      
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);  
      
            jLabel1.setText("Alunos Incluídos:");  
      
            jComboBox1.addActionListener(new java.awt.event.ActionListener() {  
                public void actionPerformed(java.awt.event.ActionEvent evt) {  
                    jComboBox1ActionPerformed(evt);  
                }  
            });  
      
            jLabel2.setText("Média do aluno:");  
      
            jButton1.setText("Fechar");  
            jButton1.addActionListener(new java.awt.event.ActionListener() {  
                public void actionPerformed(java.awt.event.ActionEvent evt) {  
                    jButton1ActionPerformed(evt);  
                }  
            });  
      
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());  
            getContentPane().setLayout(layout);  
            layout.setHorizontalGroup(  
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()  
                    .addContainerGap()  
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 194, javax.swing.GroupLayout.PREFERRED_SIZE)  
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE))  
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 65, Short.MAX_VALUE)  
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)  
                        .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE)  
                        .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 101, Short.MAX_VALUE)  
                        .addComponent(jTextField1))  
                    .addGap(30, 30, 30))  
            );  
            layout.setVerticalGroup(  
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
                .addGroup(layout.createSequentialGroup()  
                    .addGap(21, 21, 21)  
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)  
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)  
                        .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))  
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)  
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)  
                        .addComponent(jComboBox1, javax.swing.GroupLayout.DEFAULT_SIZE, 29, Short.MAX_VALUE)  
                        .addComponent(jTextField1))  
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)  
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)  
                    .addContainerGap(175, Short.MAX_VALUE))  
            );  
      
            pack();  
        }// </editor-fold>                          
      
         
        private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                             
            // TODO add your handling code here:  
              
            //CÓDIGO QUE ESTÁ GERANDO ERRO:  
              
            int posicao = this.jComboBox1.getSelectedIndex();  
            Aluno a = this.alunos.get(posicao);  
            String media = Double.toString(a.media());  
            this.jTextField1.setText(media);  
        }                                            
      
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
            // TODO add your handling code here:  
            System.exit(1);  
        }                                          
      
          
           
          
        /** 
         * @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(ListaAlunos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);  
            } catch (InstantiationException ex) {  
                java.util.logging.Logger.getLogger(ListaAlunos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);  
            } catch (IllegalAccessException ex) {  
                java.util.logging.Logger.getLogger(ListaAlunos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);  
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {  
                java.util.logging.Logger.getLogger(ListaAlunos.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() {  
                    
                }  
            });  
        }  
      
        // Variables declaration - do not modify                       
        private javax.swing.JButton jButton1;  
        private javax.swing.JComboBox jComboBox1;  
        private javax.swing.JLabel jLabel1;  
        private javax.swing.JLabel jLabel2;  
        private javax.swing.JTextField jTextField1;  
        // End of variables declaration                     
    }
Interface:
/* 
     * To change this license header, choose License Headers in Project Properties. 
     * To change this template file, choose Tools | Templates 
     * and open the template in the editor. 
     */  
      
    package pacoteInterface;  
    import java.util.ArrayList;  
    import java.sql.*;  
      
    /** 
     * 
     * @author Giseli 
     */  
    public class Interface extends javax.swing.JFrame {  
      
        /** 
         * Creates new form  
         */  
         
          
       private final ArrayList<Aluno> alunos  ; //NÃO TINHA "final"  
         
        //ArrayList<Aluno> alunos = new ArrayList<Aluno>(); //Pra teste  
        
          
          
        public Interface() { //Construtor da Classe  
             /*this.alunos = new ArrayList<Aluno>();*/  
            this.alunos = new ArrayList<>(); //ERA ASSIM: new ArrayList<Aluno>();  
            initComponents();  
        }  
          
       /* void incluirAluno (Aluno a) { 
            this.alunos.add(a); 
            
        }*/  
          
         public void mostraAluno(int i){ // teste  
            System.out.println("Nome:"+alunos.get(i).getNome());  
      
        }  
        /*public ArrayList<Aluno> getAlunos() { //ISSO NÃO TINHA 
            return alunos; 
        }*/  
         
          
        /** 
         * 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() {  
      
            jPanel1 = new javax.swing.JPanel();  
            jLabel1 = new javax.swing.JLabel();  
            jLabel2 = new javax.swing.JLabel();  
            jTextField1 = new javax.swing.JTextField();  
            jTextField2 = new javax.swing.JTextField();  
            jPanel2 = new javax.swing.JPanel();  
            jLabel3 = new javax.swing.JLabel();  
            jTextField3 = new javax.swing.JTextField();  
            jLabel4 = new javax.swing.JLabel();  
            jTextField4 = new javax.swing.JTextField();  
            jLabel5 = new javax.swing.JLabel();  
            jTextField5 = new javax.swing.JTextField();  
            jCheckBox1 = new javax.swing.JCheckBox();  
            jTextField6 = new javax.swing.JTextField();  
            jButton2 = new javax.swing.JButton();  
            jButton3 = new javax.swing.JButton();  
      
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);  
      
            jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Dados pessoais do aluno", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Agency FB", 1, 12))); // NOI18N  
      
            jLabel1.setText("Nome do aluno");  
      
            jLabel2.setText("Matrícula");  
      
            jTextField1.addActionListener(new java.awt.event.ActionListener() {  
                public void actionPerformed(java.awt.event.ActionEvent evt) {  
                    jTextField1ActionPerformed(evt);  
                }  
            });  
      
            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);  
            jPanel1.setLayout(jPanel1Layout);  
            jPanel1Layout.setHorizontalGroup(  
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
                .addGroup(jPanel1Layout.createSequentialGroup()  
                    .addContainerGap()  
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
                        .addComponent(jLabel1)  
                        .addComponent(jLabel2))  
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)  
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
                        .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 229, Short.MAX_VALUE)  
                        .addComponent(jTextField2))  
                    .addContainerGap())  
            );  
            jPanel1Layout.setVerticalGroup(  
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
                .addGroup(jPanel1Layout.createSequentialGroup()  
                    .addContainerGap()  
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)  
                        .addComponent(jLabel1)  
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))  
                    .addGap(18, 18, 1<img src="http://javafree.uol.com.br/forum/images/smiles/icon_cool.gif">  
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)  
                        .addComponent(jLabel2)  
                        .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))  
                    .addContainerGap(43, Short.MAX_VALUE))  
            );  
      
            jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Notas do aluno", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Agency FB", 1, 12))); // NOI18N  
      
            jLabel3.setText("Primeira prova");  
      
            jLabel4.setText("Segunda prova");  
      
            jLabel5.setText("Ecercicios");  
      
            jTextField5.addActionListener(new java.awt.event.ActionListener() {  
                public void actionPerformed(java.awt.event.ActionEvent evt) {  
                    jTextField5ActionPerformed(evt);  
                }  
            });  
      
            jCheckBox1.setText("Prova final");  
            jCheckBox1.addActionListener(new java.awt.event.ActionListener() {  
                public void actionPerformed(java.awt.event.ActionEvent evt) {  
                    jCheckBox1ActionPerformed(evt);  
                }  
            });  
      
            jTextField6.setEditable(false);  
            jTextField6.addActionListener(new java.awt.event.ActionListener() {  
                public void actionPerformed(java.awt.event.ActionEvent evt) {  
                    jTextField6ActionPerformed(evt);  
                }  
            });  
      
            jButton2.setText("Adicionar este aluno");  
            jButton2.addActionListener(new java.awt.event.ActionListener() {  
                public void actionPerformed(java.awt.event.ActionEvent evt) {  
                    jButton2ActionPerformed(evt);  
                }  
            });  
      
            jButton3.setText("Fechar");  
            jButton3.addActionListener(new java.awt.event.ActionListener() {  
                public void actionPerformed(java.awt.event.ActionEvent evt) {  
                    jButton3ActionPerformed(evt);  
                }  
            });  
      
            javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);  
            jPanel2.setLayout(jPanel2Layout);  
            jPanel2Layout.setHorizontalGroup(  
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
                .addGroup(jPanel2Layout.createSequentialGroup()  
                    .addGap(47, 47, 47)  
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
                        .addGroup(jPanel2Layout.createSequentialGroup()  
                            .addComponent(jButton2)  
                            .addGap(0, 0, Short.MAX_VALUE))  
                        .addGroup(jPanel2Layout.createSequentialGroup()  
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
                                .addComponent(jLabel3)  
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()  
                                    .addComponent(jLabel5)  
                                    .addGap(45, 45, 45)))  
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)  
                                .addComponent(jTextField5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 52, Short.MAX_VALUE)  
                                .addComponent(jTextField3, javax.swing.GroupLayout.Alignment.LEADING))  
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)  
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
                                .addComponent(jButton3)  
                                .addGroup(jPanel2Layout.createSequentialGroup()  
                                    .addGap(79, 79, 79)  
                                    .addComponent(jCheckBox1)  
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)  
                                    .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE))  
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()  
                                    .addComponent(jLabel4)  
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)  
                                    .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)))  
                            .addGap(51, 51, 51)))  
                    .addContainerGap())  
            );  
            jPanel2Layout.setVerticalGroup(  
                jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
                .addGroup(jPanel2Layout.createSequentialGroup()  
                    .addGap(17, 17, 17)  
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
                        .addComponent(jTextField3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)  
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)  
                            .addComponent(jLabel3)  
                            .addComponent(jTextField4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)  
                            .addComponent(jLabel4)))  
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
                        .addGroup(jPanel2Layout.createSequentialGroup()  
                            .addGap(18, 18, 1<img src="http://javafree.uol.com.br/forum/images/smiles/icon_cool.gif">  
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)  
                                .addComponent(jLabel5)  
                                .addComponent(jTextField5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))  
                        .addGroup(jPanel2Layout.createSequentialGroup()  
                            .addGap(35, 35, 35)  
                            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)  
                                .addComponent(jCheckBox1)  
                                .addComponent(jTextField6, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))  
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 26, Short.MAX_VALUE)  
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)  
                        .addComponent(jButton2)  
                        .addComponent(jButton3))  
                    .addGap(51, 51, 51))  
            );  
      
            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(33, 33, 33)  
                            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))  
                        .addGroup(layout.createSequentialGroup()  
                            .addContainerGap()  
                            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 458, javax.swing.GroupLayout.PREFERRED_SIZE)))  
                    .addContainerGap(179, Short.MAX_VALUE))  
            );  
            layout.setVerticalGroup(  
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)  
                .addGroup(layout.createSequentialGroup()  
                    .addContainerGap()  
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)  
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 54, Short.MAX_VALUE)  
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)  
                    .addContainerGap())  
            );  
      
            pack();  
        }// </editor-fold>                          
      
        public void limparCampos() { //Isso era provate  
            this.jTextField1.setText("");//O nome volta a ser vazio  
            this.jTextField2.setText("");//A matricula tambem  
            this.jTextField3.setText("0");//As notas voltam a ser zero  
            this.jTextField4.setText("0");  
            this.jTextField5.setText("0");  
            this.jTextField6.setText("0");  
            this.jCheckBox1.setSelected(false); /*O campo de seleção da prova final 
            não estará selecionado*/  
            this.jTextField6.setEditable(false);/*A princípio, o campo com a nota da  
            prova fnal não poderá ser inserido*/  
              
           
             
        }  
          
          
          
       
          
        private void inserirAlunoBD(Aluno a) {  
            //Definindo o driver do banco que será utilizado:  
            String driver = "org.apache.derby.jdbc.ClientDriver";  
            //Definindo o Banco de dados que será utilizado:  
            String url = "jdbc:derby://localhost:1527/LP";  
            //Definindo o usuário e a senha para conectarmos ao banco:  
            String username = "giseli";  
            String password = "giseli";  
              
            try {  
                //Carregando driver do BD:  
                Class.forName(driver);  
                //Estabelecendo conexão com o BD  
                Connection connection = DriverManager.getConnection(  
                url, username, password);  
                  
                  
                  
                //Criando statement para executar queries.  
                Statement statement = connection.createStatement();  
                /* o código para manipular o banco vem a partir daqui. Através do 
                "statement" criado acima, podemos inserir dados nas tabelas, recuperar dados etc. 
                Neste caso, iremos atualizar a tabela Aluno inserindo um anova linha.  
                */  
                String insert = "INSERT INTO Aluno VALUES ('" +  
                        a.getNome() + "', '" + a.getMatricula() + "', " +  
                        a.getProva1() + ", " + a.getProva2() + ", " +  
                        a.getTrabalhos() + ", " + a.getProvaFinal() + ")";  
                  
                /*A string criada é como o comando SQL a seguir: INSERT INTO Alunos  
                Values ('Hilário', '12345', 20.0, 30.0, 10.0, 0.0)*/  
                statement.executeUpdate(insert);  
                connection.close();  
            }catch(ClassNotFoundException cnfe){  
                mensagemErro("Error loading driver: " + cnfe, "ERRO");  
            }catch(SQLException sqle) {  
                mensagemErro("Error loading driver: " + sqle, "ERRO");  
            }  
            }  
          
          
        private void jCheckBox1ActionPerformed(java.awt.event.ActionEvent evt) {                                             
            boolean estado = this.jTextField6.isEditable();  
            this.jTextField6.setEditable(!estado);           // TODO add your handling code here:  
        }                                            
      
        private void jTextField5ActionPerformed(java.awt.event.ActionEvent evt) {                                              
            // TODO add your handling code here:  
        }                                             
      
        private void jTextField6ActionPerformed(java.awt.event.ActionEvent evt) {                                              
            // TODO add your handling code here:  
        }                                             
      
        private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {                                              
            // TODO add your handling code here:  
        }                                             
      
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                           
            // TODO add your handling code here:  
            String nome, matricula;  
            double nota1 = 0, nota2 = 0, nota3 = 0, provafinal = 0;  
              
            //Recuperando os campos digitados:  
            nome = this.jTextField1.getText();  
            matricula = this.jTextField2.getText();  
              
             
              
            try {  
    //Transformando as notas digitadas para Double:  
                nota1 = Double.parseDouble(this.jTextField3.getText());  
                nota2 = Double.parseDouble(this.jTextField4.getText());  
                nota3 = Double.parseDouble(this.jTextField5.getText());  
      
                //Criando um objeto da classe Aluno:  
                Aluno a = new Aluno(nome, matricula, nota1, nota2, nota3);  
                /* getAlunos().add(a);*/ //ISSO NÃO TINHA  
                //Verificando se aluno fez prova final:  
                if (this.jTextField6.isEditable()) {  
                    provafinal = Double.parseDouble(this.jTextField6.getText());  
                    a.setProvaFinal(provafinal);  
                }  
                  
                  
                 //Confirmando se os dados inseridos estão corretos  
                String mensagem = "Confira os dados do Aluno e confirme se deseja "  
                        + "adicioná-lo: \n\n";  
                mensagem += "Nome: "+ nome + "\n";  
                mensagem += "Matricula: "+ matricula + "\n";  
                mensagem += "Primeira Prova: "+ nota1 + "\n";  
                mensagem += "Segunda Prova: "+ nota2 + "\n";  
                mensagem += "Exercícios: "+ nota3 + "\n";  
                mensagem += "Média Final: "+ a.media();  
                  
                //Inserindo a nota da prova final na mensagem  
                if(this.jTextField6.isEditable()){  
                    mensagem += "Prova Final: " + provafinal + "\n";  
                }  
                  
                /*Criando uma janela de CONFIRMAÇÃO com as opções ON e CANCEL,  
                e verificando se o usuário escolheu a opção OK */  
                if(confirmacao(mensagem, "Aluno inserido")) {  
                    //Incluindo o aluno no ArrayList...  
                    inserirAlunoBD(a); //ERA ASSIM: incluirAluno(a);  
                    //Avisando que ele foi inserido...  
                    mensagemAlerta("Aluno inserido com sucesso.",  
                            "Aluno inserido!");  
                    //...e limpando os campos do formulário..  
                    this.limparCampos();  
                     
                }  
                  
                  
                inserirAlunoBD(a); //Incluindo o aluno no ArrayList  
            } catch (NumberFormatException numberFormatException) {  
                mensagemErro(  
                "Erro: alguma nota não foi digitada corretamente.",   
                "Nota inválida");  
                  
                 
                  
            }  
            this.limparCampos(); /*Limpando todos os campos para que o usuário possa  
            cadastrar um novo aluno*/        
        }                                          
      
        //MÉTODOS INSERIDOS PARA MENSAGENS  
         public static void mensagemErro(String msg, String titulo){  
                //Mostrando uma mensagem de erro ao usuário  
             javax.swing.JOptionPane.showMessageDialog(null, msg, titulo,  
                     javax.swing.JOptionPane.ERROR_MESSAGE);  
            }  
           
         public static boolean confirmacao (String msg, String titulo) {  
             /*Criando uma janela de CONFIRMAÇÃO com as opções OK e CANCEL, e retornando 
             verdadeiro se o usuario clicou em OK 
             */  
             if(javax.swing.JOptionPane.showConfirmDialog  
            (null, msg, titulo,  
             javax.swing.JOptionPane.OK_CANCEL_OPTION) ==   
             javax.swing.JOptionPane.OK_OPTION)   
               
             {  
             return true;  
            }  
             else {  
             return false;  
                  }  
               
         }  
           
         public static void mensagemAlerta (String msg, String titulo){  
             //Mostrando uma informação ao usuário  
             javax.swing.JOptionPane.showMessageDialog(null, msg, titulo,  
             javax.swing.JOptionPane.INFORMATION_MESSAGE);  
         }  
           
           
          
          
        private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                           
            // TODO add your handling code here:  
          
            setVisible(true);  
            this.dispose();  
            /*this.setVisible(false);*/ //ERA ISSO NA LINHA ANTERIOR  
        }                                          
      
        /** 
         * @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(Interface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);  
            } catch (InstantiationException ex) {  
                java.util.logging.Logger.getLogger(Interface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);  
            } catch (IllegalAccessException ex) {  
                java.util.logging.Logger.getLogger(Interface.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);  
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {  
                java.util.logging.Logger.getLogger(Interface.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 Interface().setVisible(true);  
                      
             
                      
                }  
            });  
        }  
      
        // Variables declaration - do not modify                       
        private javax.swing.JButton jButton2;  
        private javax.swing.JButton jButton3;  
        private javax.swing.JCheckBox jCheckBox1;  
        private javax.swing.JLabel jLabel1;  
        private javax.swing.JLabel jLabel2;  
        private javax.swing.JLabel jLabel3;  
        private javax.swing.JLabel jLabel4;  
        private javax.swing.JLabel jLabel5;  
        private javax.swing.JPanel jPanel1;  
        private javax.swing.JPanel jPanel2;  
        private javax.swing.JTextField jTextField1;  
        private javax.swing.JTextField jTextField2;  
        private javax.swing.JTextField jTextField3;  
        private javax.swing.JTextField jTextField4;  
        private javax.swing.JTextField jTextField5;  
        private javax.swing.JTextField jTextField6;  
        // End of variables declaration                     
    }
Criado 31 de julho de 2014
Respostas 0
Participantes 1