Conexão com banco de dados, erro na inicialização dos componentes [RESOLVIDO]

3 respostas
caike_chb
Bom dia galera, sou iniciante em java, e estou aprendendo com o prof Neri Neitzke por meio de vídeo aulas. Bem, eu estava fazendo a conexão com o banco de dados Access e quando coloquei a expressão de tratamento de erros try e catch, aconteceu alguma coisa que não consigo identificar na inicialização dos componentes
try
        {
            while(con_cadastro.resultset.next())//while (enquanto)... na classe con_cadastro retornar dados então
            {
                System.out.println(con_cadastro.resultset.getString("cad_codigo"));
                System.out.println(con_cadastro.resultset.getString("cad_descricao"));
                System.out.println(con_cadastro.resultset.getString("cad_nome"));
                System.out.println(con_cadastro.resultset.getString("cad_tipo"));
                System.out.println(con_cadastro.resultset.getString("cad_tamanho"));
            }
        }   
        catch(SQLException erro)
        {            
            JOptionPane.showMessageDialog(null,"Não localizou dados " + erro);
        }
Estou utilizando o NetBeans 7.1 e os erros aparem nas seguintes sintaxes
[b][i][color=red]nitComponents();[/color][/i][/b]
[b]  [i][color=red] @SuppressWarnings("unchecked")[/color][/i][/b]
[b][i][color=red] public static void main(String args[]) { [/color][/i][/b]
package formularios;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import utilitarios.conexao; //Importa a classe conexao
import utilitarios.conexao;
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Carlos
 */

public class jf_cadastro extends javax.swing.JFrame {

    conexao con_cadastro; //cria o objeto conexao
    public jf_cadastro() {
        i[b][i][color=red]nitComponents();[/color][/i][/b]
        con_cadastro = new conexao(); //inicia o objeto conexao
        con_cadastro.conecta(); //chama o metodo conecta() dentro da classe conexao
        con_cadastro.executeSQL("Select * from tbl_cadastro"); //chama o método executeSQL da classe conexao
        try
        {
            while(con_cadastro.resultset.next())//while (enquanto)... na classe con_cadastro retornar dados então
            {
                System.out.println(con_cadastro.resultset.getString("cad_codigo"));
                System.out.println(con_cadastro.resultset.getString("cad_descricao"));
                System.out.println(con_cadastro.resultset.getString("cad_nome"));
                System.out.println(con_cadastro.resultset.getString("cad_tipo"));
                System.out.println(con_cadastro.resultset.getString("cad_tamanho"));
            }
        }   
        catch(SQLException erro)
        {            
            JOptionPane.showMessageDialog(null,"Não localizou dados " + 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.
     */
  [b]  [i][color=red] @SuppressWarnings("unchecked")[/color][/i][/b]
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jlbl_pesquisar = new javax.swing.JLabel();
        jlbl_codigo = new javax.swing.JLabel();
        jlbl_descricao = new javax.swing.JLabel();
        jlbl_nome = new javax.swing.JLabel();
        jlbl_tipo = new javax.swing.JLabel();
        jlbl_tamanho = new javax.swing.JLabel();
        jtxt_codigo = new javax.swing.JTextField();
        jtxt_descricao = new javax.swing.JTextField();
        jtxt_nome = new javax.swing.JTextField();
        jtxt_tipo = new javax.swing.JTextField();
        jpnl_cadastro = new javax.swing.JPanel();
        jlbl_titulocadastro = new javax.swing.JLabel();
        jbtn_primeiro = new javax.swing.JButton();
        jbtn_anterior = new javax.swing.JButton();
        jbtn_proximo = new javax.swing.JButton();
        jbtn_ultimo = new javax.swing.JButton();
        jbtn_inserir = new javax.swing.JButton();
        jbtn_cancelar = new javax.swing.JButton();
        jbtn_editar = new javax.swing.JButton();
        jbtn_gravar = new javax.swing.JButton();
        jbtn_excluir = new javax.swing.JButton();
        jtxt_pesquisar = new javax.swing.JTextField();
        jcbx_pesquisar = new javax.swing.JComboBox();
        jcbx_tamanho = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jlbl_pesquisar.setText("Pesquisar:");

        jlbl_codigo.setText("Código:");

        jlbl_descricao.setText("Descrição:");

        jlbl_nome.setText("Nome:");

        jlbl_tipo.setText("Tipo:");

        jlbl_tamanho.setText("Tamanho:");

        jpnl_cadastro.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.LOWERED, null, java.awt.Color.lightGray, null, null));

        jlbl_titulocadastro.setFont(new java.awt.Font("Comic Sans MS", 3, 24)); // NOI18N
        jlbl_titulocadastro.setText("CADASTRO DE PUBLICAÇÕES");

        javax.swing.GroupLayout jpnl_cadastroLayout = new javax.swing.GroupLayout(jpnl_cadastro);
        jpnl_cadastro.setLayout(jpnl_cadastroLayout);
        jpnl_cadastroLayout.setHorizontalGroup(
            jpnl_cadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnl_cadastroLayout.createSequentialGroup()
                .addGap(117, 117, 117)
                .addComponent(jlbl_titulocadastro, javax.swing.GroupLayout.PREFERRED_SIZE, 372, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jpnl_cadastroLayout.setVerticalGroup(
            jpnl_cadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jpnl_cadastroLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jlbl_titulocadastro)
                .addContainerGap(23, Short.MAX_VALUE))
        );

        jbtn_primeiro.setText("<<");

        jbtn_anterior.setText("<");

        jbtn_proximo.setText(">");

        jbtn_ultimo.setText(">>");

        jbtn_inserir.setText("Inserir");

        jbtn_cancelar.setText("Cancelar");

        jbtn_editar.setText("Editar");

        jbtn_gravar.setText("Gravar");

        jbtn_excluir.setText("Excluir");

        jcbx_pesquisar.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jcbx_tamanho.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Médio", "Grande", "Pequeno" }));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jpnl_cadastro, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(42, 42, 42)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jlbl_descricao)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jlbl_tipo)
                                .addComponent(jlbl_nome)
                                .addComponent(jlbl_tamanho))
                            .addComponent(jlbl_pesquisar, javax.swing.GroupLayout.Alignment.TRAILING))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(189, 189, 189)
                                        .addComponent(jcbx_pesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 244, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(jcbx_tamanho, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                        .addComponent(jtxt_tipo, javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jtxt_nome, javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(jtxt_descricao, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 339, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(jtxt_pesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 167, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jtxt_codigo, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(77, 77, 77)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jbtn_primeiro)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jbtn_anterior)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jbtn_proximo)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jbtn_ultimo))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jbtn_inserir)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jbtn_cancelar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jbtn_editar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jbtn_gravar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jbtn_excluir))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(54, 54, 54)
                        .addComponent(jlbl_codigo)))
                .addContainerGap(33, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jbtn_anterior, jbtn_cancelar, jbtn_editar, jbtn_excluir, jbtn_gravar, jbtn_inserir, jbtn_primeiro, jbtn_proximo, jbtn_ultimo});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addComponent(jpnl_cadastro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(31, 31, 31)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbl_pesquisar)
                    .addComponent(jtxt_pesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jcbx_pesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 40, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbl_codigo)
                    .addComponent(jtxt_codigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbl_descricao)
                    .addComponent(jtxt_descricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbl_nome)
                    .addComponent(jtxt_nome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbl_tipo)
                    .addComponent(jtxt_tipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbl_tamanho)
                    .addComponent(jcbx_tamanho, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbtn_primeiro)
                    .addComponent(jbtn_anterior)
                    .addComponent(jbtn_proximo)
                    .addComponent(jbtn_ultimo))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbtn_inserir)
                    .addComponent(jbtn_cancelar)
                    .addComponent(jbtn_editar)
                    .addComponent(jbtn_gravar)
                    .addComponent(jbtn_excluir))
                .addGap(35, 35, 35))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-578)/2, (screenSize.height-478)/2, 578, 478);
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    [b][i][color=red] public static void main(String args[]) { [/color][/i][/b]
        /*
         * 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(jf_cadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(jf_cadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(jf_cadastro.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(jf_cadastro.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 jf_cadastro().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton jbtn_anterior;
    private javax.swing.JButton jbtn_cancelar;
    private javax.swing.JButton jbtn_editar;
    private javax.swing.JButton jbtn_excluir;
    private javax.swing.JButton jbtn_gravar;
    private javax.swing.JButton jbtn_inserir;
    private javax.swing.JButton jbtn_primeiro;
    private javax.swing.JButton jbtn_proximo;
    private javax.swing.JButton jbtn_ultimo;
    private javax.swing.JComboBox jcbx_pesquisar;
    private javax.swing.JComboBox jcbx_tamanho;
    private javax.swing.JLabel jlbl_codigo;
    private javax.swing.JLabel jlbl_descricao;
    private javax.swing.JLabel jlbl_nome;
    private javax.swing.JLabel jlbl_pesquisar;
    private javax.swing.JLabel jlbl_tamanho;
    private javax.swing.JLabel jlbl_tipo;
    private javax.swing.JLabel jlbl_titulocadastro;
    private javax.swing.JPanel jpnl_cadastro;
    private javax.swing.JTextField jtxt_codigo;
    private javax.swing.JTextField jtxt_descricao;
    private javax.swing.JTextField jtxt_nome;
    private javax.swing.JTextField jtxt_pesquisar;
    private javax.swing.JTextField jtxt_tipo;
    // End of variables declaration
}

3 Respostas

C

Aff cara, complicado achar o erro nisso em…
faz o seguinte, quando eu tenho que achar eu erro que realmente não consigo identificar eu faço o seguinte: comento uma linha de cada vez dentro do meu método main ou aonde eu imagino que esteja o erro, as vezes comento métodos inteiros.
Pode acontecer do netbeans acusar erro em um trecho de código mas o que pode estar ocasionando ele pode ser outro. Se eu tivesse na sua situação eu começaria comentando assim:

conexao con_cadastro; //cria o objeto conexao  
    public jf_cadastro() {  
       // i[b][i][color=red]nitComponents();[/color][/i][/b] --->comentando aqui!!!!!!  
        con_cadastro = new conexao(); //inicia o objeto conexao  
        con_cadastro.conecta(); //chama o metodo conecta() dentro da classe conexao  
        con_cadastro.executeSQL("Select * from tbl_cadastro"); //chama o método executeSQL da classe conexao

assim por diante linha por linha

Cornelius

o man, não ficou muito claro sua questão: O programa nem compila ou não mostra a instrução SQL sua?

initComponents()

Só pra constar esse método ai de cima, o NetBeans cria para inicializar os componentes da tela que você fez (botões, caixa de texto, labels etc).

@SuppressWarnings("unchecked")

isso aqui é só uma anotação!

public static void main(String args[])

Esse é o metodo principal da sua aplicacao. A JVM le ela primeiro quando o programa é executado!

Acho que era bom voce postar o codigo da sua conexao ao banco, vc acessa o Access via ODBC? Se sim, já criou o a conexao ODBC na sua maquina? Da uma ligada nesse site:

Espero ter ajudado!

caike_chb
Cornelius o código da minha conexão é o seguinte:
package utilitarios;
import java.sql.*;
import javax.swing.*;

public class conexao
{
    final private String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
    /* final -> significa que a variável é constante, não poderá ser alterada
     * private -> pertence somente a esta classe
     * String -> é um texto
     * o Driver para carregar banco de dados do tipo Access é "sun.jdbc.odbc.JdbcOdbcDriver"
     */
    final private String url = "jdbc:odbc:publicacoes_tj";
    // a variável url armazena a fonte de dados odbc do Access
    final private String usuario = "";
    final private String senha = "";
    private Connection conexao;
    //Criando um objeto conexao que é do tipo Connection e é Privado
    public Statement statement;
    //O objeto do tipo Statement é responsavel para abrir caminho até o local do Banco de Dados
    public ResultSet resultset;
    //O Obj ResultSet é responsavel por armazenar todos os comandos de SQL
    
    //criar método para conexão
    public boolean conecta()
    {
        boolean result = true;
        /* try e catch no java serve para tratamento de erros
         * no java, se for ultilizar dados externos, como um banco de dados por exemplo
         * e não fizer o tratamento de erros, o sistema não irá funcionar
         * é necessário que seja tratado antes de se ultilizar dados de fontes externas
         */
        try
            {
                Class.forName(driver);
                conexao = DriverManager.getConnection(url, usuario,senha);
                // O java vai tentar carregar uma classe com o método forName que efetua o carregamento do Driver -> Class.forName(Driver)
                //JOptionPane.showMessageDialog(null, "Conectou");
            }
        catch(ClassNotFoundException Driver) // Esta variável Driver receberá o erro de conexão se houver
            {
                JOptionPane.showMessageDialog(null, "Driver não localizado: "+ Driver);
                result = false;
            }
        catch(SQLException Fonte)//Caso o erro chegue nesta parte, pode ser erro com Banco de Dados, ou não existe, ou algum campo não foi criado
            {
                JOptionPane.showMessageDialog(null, "Deu erro na conexão "+
                    "com a fonte de dados: "+ Fonte);
                result = false;
            }
        return result;
    }
    
     public void desconecta()
     {
         boolean result = true;
         try
         {
             conexao.close();
             JOptionPane.showMessageDialog(null, "banco fechado");
         }
         catch(SQLException fecha)
         {
             JOptionPane.showMessageDialog(null, "Não foi possível" +
                     "fechar o banco de dados: " + fecha.getMessage());
             result = false;
         }
     }
     
     public void executeSQL(String sql)
     {
         try
         {
             statement = conexao.createStatement(
                     ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
             resultset = statement.executeQuery(sql);
         }
         catch(SQLException sqlex)
         {
             JOptionPane.showMessageDialog(null,"Não foi possível "+
                     "executar o comando sql" +sqlex +
                     ", o sql passado foi " + sql);
         }
     }
    
}

Eu estou conseguindo abrir agora... mas só pode ficar do netbeans, se eu jogo ele, mesmo refatorando para outro pacote, ele não funciona! O que eu faço para colocar ele num pacote Formulários por exemplo?
Obrigao

Criado 14 de março de 2012
Ultima resposta 15 de mar. de 2012
Respostas 3
Participantes 3