O Que ha de errado com este código

2 respostas
_

Estou tentando criar um programa que abre uma tabela e quando eu clicar em um botão ele mostre em um txt o primeiro registro da tabela, mas não está dando certo, eu sou novato em java e devo estar fazendo um monte de bobagens mas sinceramente não consigo saber nem qual é a besteira que estou fazendo gostaria de saber se alguem pode me ajudar. o código está abaixo.

Código:

////Importa os paotes necessários

import java.awt.<em>;

import java.awt.event.</em>;

import java.io.FileNotFoundException;
import java.io.IOException;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import javax.swing.*;

import sun.rmi.transport.Connection;

/** Classe

  • [ coloque aqui a descrição da classe ]

  • @author Fernando Anselmo © Jul - 2005

  • @version 1.0
    */
    public class JthM002Jt extends JFrame {
    Connection db; // Conexão com o servidor de banco de dados
    Statement st; // Declaração para executar os comandos

    public void go() throws ClassNotFoundException, FileNotFoundException,
    
    IOException, SQLException
    
    {
    
    // Banco de dados, usuário e senha igual a teste
    
    // CREATE USER teste WITH password teste;
    
    // CREATE DATABASE teste WITH OWNER teste ENCODING LATIN1;
    
    String url = jdbc:postgresql://localhost/Jethro?charSet=Jethro;
    
    String usr = postgres;
    
    String pwd = pgadmin;
    

    // Carregar o driver
    Class.forName(“org.postgresql.Driver”);

    // Conectar com o servidor de banco de dados
    
    System.out.println("Conectando ao banco de dados\nURL = " + url);
    
    db = (Connection) DriverManager.getConnection(url, usr, pwd);
    
    // Fechar a conexão
    
    System.out.println(Fechando a conexão);
    
    st.close();
    
    db.close();
    
    }
    
    // Bloco 1 - Dados dos Objetos da Janela
    
    private JButton Bt_Primeiro;
    
    private JButton Bt_Anterior;
    
    private JButton Bt_Salvar;
    
    private JButton Bt_Proximo;
    
    private JButton Bt_Editar;
    
    private JButton Bt_Excluir;
    
    private JButton Bt_Novo;
    
    private JButton Bt_Ultimo;
    
    private JButton Bt_Cancelar;
    
    private JLabel  Lbl_Inicio;
    
    private JLabel  Lbl_Anterior;
    
    // Bloco 1 - Dados dos Objetos da Janela
    
    private JLabel objeto1;
    
    private JTextField TXT_CodigoParceiro;
    
    private JLabel objeto6;
    
    private JPasswordField TXT_NomeParceiro;
    
    private JLabel objeto9;
    
    private JRadioButton RB_PessoaFisica;
    
    private JRadioButton RB_PessoaJuridica;
    
    private JTextField TXT_CNPJ;
    
    private JLabel objeto13;
    
    private JTextField TXT_InscricaoEstadual;
    
    private JTextField TXT_InscricaoMunicipal;
    
    private JLabel objeto16;
    
    private JLabel objeto17;
    
    public JthM002Jt() {
    
    try {
    
    mostra();
    
    } catch(Exception ex) {
    
    ex.printStackTrace();
    
    }
    
    }
    
    private void mostra() {
    
    //Icones Utilizados
    
    // Bloco 2 - Dados da Criação da Janela
    
    this.getContentPane().setLayout(null);
    
    this.getContentPane().setBackground(new Color(204, 204, 204));
    
    this.setSize(656, 400);
    
    this.setLocation(100, 113);
    
    this.setTitle("Jethro - [JthM001Jt  - 01.01] Manutenção da Tabela de Parceiros  ");
    
    this.setResizable(false);
    
    // Bloco 3 - Dados da Criação dos Controles na Janela 
        //////CODIGO DO PARCEIRO 
        objeto1 = new JLabel("Codigo:"); 
        objeto1.setBounds(new Rectangle(5, 83, 57, 13)); 
        this.getContentPane().add(objeto1, null); 
        TXT_CodigoParceiro = new JTextField(); 
        TXT_CodigoParceiro.setBounds(new Rectangle(70, 75, 100, 21)); 
        this.getContentPane().add(TXT_CodigoParceiro, null); 
      //////CNPJ DO PARCEIRO 
      TXT_CNPJ = new JTextField(); 
      TXT_CNPJ.setBounds(new Rectangle(400, 75, 150, 21)); 
      this.getContentPane().add(TXT_CNPJ, null); 
      objeto13 = new JLabel("CNPJ"); 
      objeto13.setBounds(new Rectangle(342, 83, 57, 13)); 
      this.getContentPane().add(objeto13, null); 
    
        objeto6 = new JLabel("Categoria:"); 
        objeto6.setBounds(new Rectangle(5, 130, 70, 13)); 
        this.getContentPane().add(objeto6, null); 
        TXT_NomeParceiro = new JPasswordField(); 
        TXT_NomeParceiro.setBounds(new Rectangle(70, 200, 479, 21)); 
        this.getContentPane().add(TXT_NomeParceiro, null); 
        objeto9 = new JLabel("Nome:"); 
        objeto9.setBounds(new Rectangle(5, 208, 57, 13)); 
        this.getContentPane().add(objeto9, null); 
        RB_PessoaFisica = new JRadioButton("Pessoa Física"); 
        RB_PessoaFisica.setBounds(new Rectangle(191,150, 110, 30)); 
        this.getContentPane().add(RB_PessoaFisica, null); 
        RB_PessoaJuridica = new JRadioButton("Pessoa Jurídica"); 
        RB_PessoaJuridica.setBounds(new Rectangle(337,150, 120, 30)); 
        this.getContentPane().add(RB_PessoaJuridica, null); 
        TXT_InscricaoEstadual = new JTextField(); 
        TXT_InscricaoEstadual.setBounds(new Rectangle(122, 250, 150, 21)); 
        this.getContentPane().add(TXT_InscricaoEstadual, null); 
        TXT_InscricaoMunicipal = new JTextField("Inscrição Estadual:"); 
        TXT_InscricaoMunicipal.setBounds(new Rectangle(400, 250, 150, 21)); 
        this.getContentPane().add(TXT_InscricaoMunicipal, null); 
        objeto16 = new JLabel("Inscrição Estadual:"); 
        objeto16.setBounds(new Rectangle(5, 258, 200, 13)); 
        this.getContentPane().add(objeto16, null); 
      objeto17 = new JLabel("Inscrição Municipal:"); 
      objeto17.setBounds(new Rectangle(280, 258, 115, 13)); 
        this.getContentPane().add(objeto17, null); 
         //Botões do Painel de Navegação 
      Icon Anterior   = new ImageIcon("C:/Dsystem/Img/Java/Bt_Anterior_Lig.JPG"); 
      Icon Proximo    = new ImageIcon("C:/Dsystem/Img/Java/Bt_Proximo_Lig.JPG"); 
      Icon Ultimo     = new ImageIcon("C:/Dsystem/Img/Java/Bt_Final_Lig.JPG"); 
      Icon Salvar     = new ImageIcon("C:/Dsystem/Img/Java/Bt_Gravar_Lig.JPG"); 
      Icon Excluir     = new ImageIcon("C:/Dsystem/Img/Java/Bt_Excluir_Lig.JPG"); 
      Icon Editar     = new ImageIcon("C:/Dsystem/Img/Java/Bt_Editar_Lig.JPG"); 
      Icon Cancelar     = new ImageIcon("C:/Dsystem/Img/Java/Bt_Cancelar_Lig.JPG"); 
      Icon Atualizar  = new ImageIcon("C:/Dsystem/Img/Java/Bt_Atualizar_Lig.JPG"); 
      Icon Novo        = new ImageIcon("C:/Dsystem/Img/Java/Bt_Novo_Lig.JPG"); 
         //Primeiro Registro 
      Icon Inicio  = new ImageIcon("C:/Dsystem/Img/Java/Bt_Inicio_Lig.JPG"); 
      Bt_Primeiro = new JButton(""); 
      Bt_Primeiro.setIcon(Inicio); 
      Bt_Primeiro.setBounds(new Rectangle(003, 7, 55, 55)); 
      this.getContentPane().add(Bt_Primeiro, null);
    

    ////////////////////////////////////////////////////////////////////////////////////
    ////MINHA INTENÇÃO NESTE PONTO É EXECYTAR O RESULT SET DE FORMA QUE ////////////////
    ////ELE ME COLOQUE O RESULTADO NO txt_cODIGOpARCEIRO////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////////////////////////////

    Bt_Primeiro.addMouseListener (new MouseAdapter() { 
      public void mouseClicked(MouseEvent e)    { 
      // Chamada a um método 
      Statement st = null;   // Declaração para executar os comandos       
    
         try { 
            char   Virgula = ','; 
            char   Aspas   = '"'; 
            String Str ="select   *  from "   + Aspas + 
                        "Representante" + Aspas; 
            ResultSet rs = st.executeQuery(Str); 
            TXT_CodigoParceiro.setText(Str); 
         } catch (SQLException e1) { 
            // TODO Auto-generated catch block 
            e1.printStackTrace(); 
         } 
          
          
         //////////////////////////////////////////////////////////////////////////////////// 
         ////MINHA INTENÇÃO NESTE PONTO É EXECYTAR O RESULT SET DE FORMA QUE //////////////// 
         ////ELE ME COLOQUE O RESULTADO NO txt_cODIGOpARCEIRO//////////////////////////////// 
         //////////////////////////////////////////////////////////////////////////////////// 
         //////////////////////////////////////////////////////////////////////////////////// 
          
          
    
    
    
      } 
      });
    

    }

    /**

    • @param adapter
      */

    // Insira aqui os métodos para os eventos

    public static void main(String args[]) {
    new JthM002Jt().show();

    }
    }

2 Respostas

saoj

Sem brincadeira. Teu código está muito longo e difícil de entender. Sem contar que não está formatado (indentado). Procura no Google um programinha muito poderoso chamado JACOBE. Java Code Beautifier.

:wink:

Veja se não ficou melhor. Acho que agora té vc mesmo consegue ver o erro:

////Importa os paotes necessários 
import java.awt.*; 
import java.awt.event.*; 
import java.io.FileNotFoundException; 

import java.io.IOException; 
import java.sql.DriverManager; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 

import javax.swing.*; 

import sun.rmi.transport.Connection; 


/** Classe 
 * [ coloque aqui a descrição da classe ] 
 * @author Fernando Anselmo © Jul - 2005 
 * @version 1.0 
 */ 
public class JthM002Jt extends JFrame { 
    Connection db; // Conexão com o servidor de banco de dados 
    Statement st; // Declaração para executar os comandos 

    public void go() throws ClassNotFoundException, FileNotFoundException, 
            IOException, SQLException { 
        // Banco de dados, usuário e senha igual a "teste" 
        // CREATE USER teste WITH password 'teste'; 
        // CREATE DATABASE teste WITH OWNER teste ENCODING 'LATIN1'; 
        String url = "jdbc:postgresql://localhost/Jethro?charSet=Jethro"; 
        String usr = "postgres"; 
        String pwd = "pgadmin"; 

        // Carregar o driver 
        Class.forName("org.postgresql.Driver"); 

        // Conectar com o servidor de banco de dados 
        System.out.println("Conectando ao banco de dados\nURL = " + url); 
        db = (Connection) DriverManager.getConnection(url, usr, pwd); 

        // Fechar a conexão 
        System.out.println("Fechando a conexão"); 
        st.close(); 
        db.close(); 
    } 

    // Bloco 1 - Dados dos Objetos da Janela 
    private JButton Bt_Primeiro; 
    private JButton Bt_Anterior; 
    private JButton Bt_Salvar; 
    private JButton Bt_Proximo; 
    private JButton Bt_Editar; 
    private JButton Bt_Excluir; 
    private JButton Bt_Novo; 
    private JButton Bt_Ultimo; 
    private JButton Bt_Cancelar; 
    private JLabel Lbl_Inicio; 
    private JLabel Lbl_Anterior; 

    // Bloco 1 - Dados dos Objetos da Janela 
    private JLabel objeto1; 
    private JTextField TXT_CodigoParceiro; 
    private JLabel objeto6; 
    private JPasswordField TXT_NomeParceiro; 
    private JLabel objeto9; 
    private JRadioButton RB_PessoaFisica; 
    private JRadioButton RB_PessoaJuridica; 
    private JTextField TXT_CNPJ; 
    private JLabel objeto13; 
    private JTextField TXT_InscricaoEstadual; 
    private JTextField TXT_InscricaoMunicipal; 
    private JLabel objeto16; 
    private JLabel objeto17; 
    public JthM002Jt() { 
        try { 
            mostra(); 
        } catch (Exception ex) { 
            ex.printStackTrace(); 
        } 
    } 

    private void mostra() { 
        //Icones Utilizados 
        // Bloco 2 - Dados da Criação da Janela 
        this.getContentPane().setLayout(null); 
        this.getContentPane().setBackground(new Color(204, 204, 204)); 
        this.setSize(656, 400); 
        this.setLocation(100, 113); 
        this.setTitle("Jethro - [JthM001Jt - 01.01] Manutenção da Tabela de Parceiros "); 
        this.setResizable(false); 

        // Bloco 3 - Dados da Criação dos Controles na Janela 
        //////CODIGO DO PARCEIRO 
        objeto1 = new JLabel("Codigo:"); 
        objeto1.setBounds(new Rectangle(5, 83, 57, 13)); 
        this.getContentPane().add(objeto1, null); 
        TXT_CodigoParceiro = new JTextField(); 
        TXT_CodigoParceiro.setBounds(new Rectangle(70, 75, 100, 21)); 
        this.getContentPane().add(TXT_CodigoParceiro, null); 
        //////CNPJ DO PARCEIRO 
        TXT_CNPJ = new JTextField(); 
        TXT_CNPJ.setBounds(new Rectangle(400, 75, 150, 21)); 
        this.getContentPane().add(TXT_CNPJ, null); 
        objeto13 = new JLabel("CNPJ"); 
        objeto13.setBounds(new Rectangle(342, 83, 57, 13)); 
        this.getContentPane().add(objeto13, null); 

        objeto6 = new JLabel("Categoria:"); 
        objeto6.setBounds(new Rectangle(5, 130, 70, 13)); 
        this.getContentPane().add(objeto6, null); 
        TXT_NomeParceiro = new JPasswordField(); 
        TXT_NomeParceiro.setBounds(new Rectangle(70, 200, 479, 21)); 
        this.getContentPane().add(TXT_NomeParceiro, null); 
        objeto9 = new JLabel("Nome:"); 
        objeto9.setBounds(new Rectangle(5, 208, 57, 13)); 
        this.getContentPane().add(objeto9, null); 
        RB_PessoaFisica = new JRadioButton("Pessoa Física"); 
        RB_PessoaFisica.setBounds(new Rectangle(191, 150, 110, 30)); 
        this.getContentPane().add(RB_PessoaFisica, null); 
        RB_PessoaJuridica = new JRadioButton("Pessoa Jurídica"); 
        RB_PessoaJuridica.setBounds(new Rectangle(337, 150, 120, 30)); 
        this.getContentPane().add(RB_PessoaJuridica, null); 
        TXT_InscricaoEstadual = new JTextField(); 
        TXT_InscricaoEstadual.setBounds(new Rectangle(122, 250, 150, 21)); 
        this.getContentPane().add(TXT_InscricaoEstadual, null); 
        TXT_InscricaoMunicipal = new JTextField("Inscrição Estadual:"); 
        TXT_InscricaoMunicipal.setBounds(new Rectangle(400, 250, 150, 21)); 
        this.getContentPane().add(TXT_InscricaoMunicipal, null); 
        objeto16 = new JLabel("Inscrição Estadual:"); 
        objeto16.setBounds(new Rectangle(5, 258, 200, 13)); 
        this.getContentPane().add(objeto16, null); 
        objeto17 = new JLabel("Inscrição Municipal:"); 
        objeto17.setBounds(new Rectangle(280, 258, 115, 13)); 
        this.getContentPane().add(objeto17, null); 
        //Botões do Painel de Navegação 
        Icon Anterior = new ImageIcon("C:/Dsystem/Img/Java/Bt_Anterior_Lig.JPG"); 
        Icon Proximo = new ImageIcon("C:/Dsystem/Img/Java/Bt_Proximo_Lig.JPG"); 
        Icon Ultimo = new ImageIcon("C:/Dsystem/Img/Java/Bt_Final_Lig.JPG"); 
        Icon Salvar = new ImageIcon("C:/Dsystem/Img/Java/Bt_Gravar_Lig.JPG"); 
        Icon Excluir = new ImageIcon("C:/Dsystem/Img/Java/Bt_Excluir_Lig.JPG"); 
        Icon Editar = new ImageIcon("C:/Dsystem/Img/Java/Bt_Editar_Lig.JPG"); 
        Icon Cancelar = new ImageIcon("C:/Dsystem/Img/Java/Bt_Cancelar_Lig.JPG"); 
        Icon Atualizar = new ImageIcon("C:/Dsystem/Img/Java/Bt_Atualizar_Lig.JPG"); 
        Icon Novo = new ImageIcon("C:/Dsystem/Img/Java/Bt_Novo_Lig.JPG"); 
        //Primeiro Registro 
        Icon Inicio = new ImageIcon("C:/Dsystem/Img/Java/Bt_Inicio_Lig.JPG"); 

        Bt_Primeiro = new JButton(""); 
        Bt_Primeiro.setIcon(Inicio); 
        Bt_Primeiro.setBounds(new Rectangle(003, 7, 55, 55)); 
        this.getContentPane().add(Bt_Primeiro, null); 
        //////////////////////////////////////////////////////////////////////////////////// 
        ////MINHA INTENÇÃO NESTE PONTO É EXECYTAR O RESULT SET DE FORMA QUE //////////////// 
        ////ELE ME COLOQUE O RESULTADO NO txt_cODIGOpARCEIRO//////////////////////////////// 
        //////////////////////////////////////////////////////////////////////////////////// 
        //////////////////////////////////////////////////////////////////////////////////// 

        Bt_Primeiro.addMouseListener(new MouseAdapter() { 
                public void mouseClicked(MouseEvent e) { 
                    // Chamada a um método 
                    Statement st = null; // Declaração para executar os comandos 

                    try { 
                        char Virgula = ','; 
                        char Aspas = '"'; 
                        String Str = "select * from " + Aspas + 
                            "Representante" + Aspas; 
                        ResultSet rs = st.executeQuery(Str); 

                        TXT_CodigoParceiro.setText(Str); 
                    } catch (SQLException e1) { 
                        // TODO Auto-generated catch block 
                        e1.printStackTrace(); 
                    } 

                    //////////////////////////////////////////////////////////////////////////////////// 
                    ////MINHA INTENÇÃO NESTE PONTO É EXECYTAR O RESULT SET DE FORMA QUE //////////////// 
                    ////ELE ME COLOQUE O RESULTADO NO txt_cODIGOpARCEIRO//////////////////////////////// 
                    //////////////////////////////////////////////////////////////////////////////////// 
                    //////////////////////////////////////////////////////////////////////////////////// 





                } 
            }
        ); 

    } 

    /** 
     * @param adapter 
     */ 

    // Insira aqui os métodos para os eventos 

    public static void main(String args[]) { 
        new JthM002Jt().show(); 

    } 
}
saoj

Desculpa. Não vi que vc era novato em Java, logo não tinha como vc conhecer o Jacobe nem as convenções de formatação de código.

Vc vai ter que debugar o seu código, linha a linha para descobrir onde está o problema, não tem jeito.

Criado 2 de agosto de 2005
Ultima resposta 2 de ago. de 2005
Respostas 2
Participantes 2