Carregar um jcombobox com dados do banco

Java

05/01/2012

Ae galera sou novo no forum e queria carregas os estados do meu banco em um combobox Se alguem puder me ajudar agradeço muito!!! Consulta o banco
public ResultSet ConsultarEstado(){
        Connection conexao = Banco.getConexao();
        try {            
            Statement stmt = conexao.createStatement();
            String sql = "select * from estado";                    
            resultado = stmt.executeQuery(sql);            
            } catch (Exception erro) {
            System.out.println(" Erro ao consultar estado: "+erro);
        }
     return resultado;   
    }
Windson Amorim

Windson Amorim

Curtidas 0

Respostas

Windson Amorim

Windson Amorim

05/01/2012

estados? seria tipo UF? se for isso, será que realmente é necessário fazer uma consulta ao banco só pra isso?
GOSTEI 0
Windson Amorim

Windson Amorim

05/01/2012

é e em outro combo foi colocar as cidades do estado selecionado no primeiro combo e todos os estados e cidades já estão no banco
GOSTEI 0
Windson Amorim

Windson Amorim

05/01/2012

Vou lhe dar algumas dicas... [i]*[/i] Não use [b]Statement[/b], prefira usar o [b]PreparedStatement[/b], pois ele é mais seguro. [i]*[/i] Pegue o objeto do [b]ResultSet[/b] e faça como este modelo:
PreparedStatement ps //...
ResultSet rs = ps.executeQuery();

while(rs.next()){
      // Você pega os dados usando rs.getString (caso for String), rs.getInt (caso for int) etc...
}
[i]EDIT:[/i] [i]*[/i] Para por os dados em um [i]jComboBox[/i] faça isto (coloque este código dentro do [i]while[/i]):
SeuComboBox.addItem(rs.getString(1)); // Lembrando que o 1 é o valor correspondente a sua primeira coluna do banco,
//caso for a segunda bote 2 e assim sucessivamente
para garantir, coloque em seu código também:
seuComboBox.updateUI; // Isto atualiza o JComboBox
[i][Códigos não testados em nenhuma IDE][/i] bom, siga essas dicas, provavelmente vão ajudá-lo! :!: :!:
GOSTEI 0
Douglas Eric

Douglas Eric

05/01/2012

sim ae eu enquanto estou no while carrega no combo com addItem?
GOSTEI 0
Windson Amorim

Windson Amorim

05/01/2012

[quote="wingaspar"]sim ae eu enquanto estou no while carrega no combo com addItem?
Está comentado ali no post, coloque o [b]addItem[/b] dentro do [i]while[/i].
GOSTEI 0
Douglas Eric

Douglas Eric

05/01/2012

então eu fix esse codigo e coloquei no final do jframe
public void PreencherCombo(){
    Fornecedor f = new Fornecedor();
    f.ConsultarEstado
        try {
            while (resultado.next()){
                jCEstado.addItem(resultado.getString("Nome_est"));
            }
        } catch (SQLException ex) {
            Logger.getLogger(Cadatro_Fornecedor.class.getName()).log(Level.SEVERE, null, ex);
        }
}
GOSTEI 0
Windson Amorim

Windson Amorim

05/01/2012

[quote="wingaspar"]então eu fix esse codigo e coloquei no final do jframe
public void PreencherCombo(){
    Fornecedor f = new Fornecedor();
    f.ConsultarEstado
        try {
            while (resultado.next()){
                jCEstado.addItem(resultado.getString("Nome_est"));
            }
        } catch (SQLException ex) {
            Logger.getLogger(Cadatro_Fornecedor.class.getName()).log(Level.SEVERE, null, ex);
        }
}
ai rodei e nã puxou do fazendo algo errado?
GOSTEI 0
Douglas Eric

Douglas Eric

05/01/2012

[quote="wingaspar"][quote="wingaspar"]então eu fix esse codigo e coloquei no final do jframe
public void PreencherCombo(){
    Fornecedor f = new Fornecedor();
    f.ConsultarEstado
        try {
            while (resultado.next()){
                jCEstado.addItem(resultado.getString("Nome_est"));
            }
        } catch (SQLException ex) {
            Logger.getLogger(Cadatro_Fornecedor.class.getName()).log(Level.SEVERE, null, ex);
        }
}
ai rodei e nã puxou do fazendo algo errado?
Invés de pôr, "Nome_est", bota o número correspondente à coluna dos Estados do seu Banco de Dados.
GOSTEI 0
Windson Amorim

Windson Amorim

05/01/2012

Classe Fornecedor
package jne;

import java.sql.*;
import javax.swing.*;

public class Fornecedor {
private String Razao_Social,CNPJ,Ins_Estadual,
        End,CEP,Bairro,Estado,UF,Email,Tel;
ResultSet resultado;

    public String getRazao_Social() {
        return Razao_Social;
    }
    public void setRazao_Social(String Razao_Social) {
        this.Razao_Social = Razao_Social;
    }
    public String getCNPJ() {
        return CNPJ;
    }
    public void setCNPJ(String CNPJ) {
        this.CNPJ = CNPJ;
    }
    public String getIns_Estadual() {
        return Ins_Estadual;
    }
    public void setIns_Estadual(String Ins_Estadual) {
        this.Ins_Estadual = Ins_Estadual;
    }
    public String getEnd() {
        return End;
    }
    public void setEnd(String End) {
        this.End = End;
    }
    public String getCEP() {
        return CEP;
    }
    public void setCEP(String CEP) {
        this.CEP = CEP;
    }
    public String getBairro() {
        return Bairro;
    }
    public void setBairro(String Bairro) {
        this.Bairro = Bairro;
    }
    public String getEstado() {
        return Estado;
    }
    public void setEstado(String Estado) {
        this.Estado = Estado;
    }
    public String getUF() {
        return UF;
    }
    public void setUF(String UF) {
        this.UF = UF;
    }
    public String getEmail() {
        return Email;
    }
    public void setEmail(String Email) {
        this.Email = Email;
    }
    public String getTel() {
        return Tel;
    }
    public void setTel(String Tel) {
        this.Tel = Tel;
    }
    
     public void Cadastrar_Fornecedor(){
        Connection conexao = Banco.getConexao();        
        try {
            Statement stmt = conexao.createStatement();
            String sql = "insert into fornecedor (Razao_Social,CNPJ,Ins_Estadual,End,CEP,Bairro,Estado,UF,Email,Tel) values "
                    + "('"+Razao_Social+"','"+CNPJ+"','"+Ins_Estadual+"','"+End+"','"+CEP+"','"+Bairro+"','"+Estado+"','"+UF+"','"+Email+"','"+Tel+"')";
            stmt.execute(sql);
            JOptionPane.showMessageDialog(null, "Cadastro realizado com sucesso !");
        } catch (Exception erro) {
            System.out.println("Erro ao cadastrar Fornecedor: "+erro);
        }
       }
     
       public ResultSet ConsultarEstado(){
        Connection conexao = Banco.getConexao();
        try {            
            Statement stmt = conexao.createStatement();
            String sql = "select * from estado";                    
            resultado = stmt.executeQuery(sql);            
            } catch (Exception erro) {
            System.out.println(" Erro ao consultar estado: "+erro);
        }
     return resultado;   
    }
}
Classe Banco
package jne;
import java.sql.Connection;
import java.sql.DriverManager;
public class Banco {
      public static Connection getConexao() {
        Connection conexao = null;
        try {
            //driver que será utilizado
            Class.forName("com.mysql.jdbc.Driver");
            //cria um objeto de conexao com um banco especificado no caminho...
            conexao = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jne", "root", "123");
        } catch (Exception erro) {
            System.out.println(erro);
        }
        return conexao;
    }
}
GOSTEI 0
Douglas Eric

Douglas Eric

05/01/2012

Ahhhh... talvez o erro seja no seu comando SQL! Tente isto como instrução SQL:
SELECT nome_est FROM estado
GOSTEI 0
Windson Amorim

Windson Amorim

05/01/2012

não deu certo veio esse é o meu frame
package Telas;

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import jne.*;

public class Cadatro_Fornecedor extends javax.swing.JFrame {
 ResultSet resultado;
   
    public Cadatro_Fornecedor() {
        initComponents();
        setLocationRelativeTo(null);
    }      

    @SuppressWarnings("unchecked")
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jBCadastrar = new javax.swing.JButton();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jTCNPJ = new javax.swing.JTextField();
        jTInsEst = new javax.swing.JTextField();
        jTRazSoc = new javax.swing.JTextField();
        jTEnd = new javax.swing.JTextField();
        jTBairro = new javax.swing.JTextField();
        jCEstado = new javax.swing.JComboBox();
        jCUF = new javax.swing.JComboBox();
        jTEmail = new javax.swing.JTextField();
        jTTel = new javax.swing.JTextField();
        jTCEP = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        jTNum = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastro de Fornecedor");

        jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 11));
        jLabel1.setText("CNPJ");

        jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 11));
        jLabel2.setText("Razão Social");

        jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 11));
        jLabel3.setText("Endereço");

        jLabel5.setFont(new java.awt.Font("Times New Roman", 1, 11));
        jLabel5.setText("Bairro");

        jLabel6.setFont(new java.awt.Font("Times New Roman", 1, 11));
        jLabel6.setText("CEP");

        jLabel7.setFont(new java.awt.Font("Times New Roman", 1, 11));
        jLabel7.setText("Estado");

        jLabel8.setFont(new java.awt.Font("Times New Roman", 1, 11));
        jLabel8.setText("UF");

        jBCadastrar.setFont(new java.awt.Font("Times New Roman", 1, 11)); // NOI18N
        jBCadastrar.setText("Cadastrar");
        jBCadastrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBCadastrarActionPerformed(evt);
            }
        });

        jLabel9.setFont(new java.awt.Font("Times New Roman", 1, 11));
        jLabel9.setText("Telefone");

        jLabel10.setFont(new java.awt.Font("Times New Roman", 1, 11));
        jLabel10.setText("E-Mail");

        jLabel11.setFont(new java.awt.Font("Times New Roman", 1, 11));
        jLabel11.setText("Ins. Estadual");

        jTCNPJ.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jTInsEst.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jTRazSoc.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jTEnd.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jTBairro.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jCEstado.setFont(new java.awt.Font("Times New Roman", 1, 11)); // NOI18N
        jCEstado.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jCUF.setFont(new java.awt.Font("Times New Roman", 1, 11));
        jCUF.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jTEmail.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jTTel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jTCEP.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel12.setFont(new java.awt.Font("Times New Roman", 1, 11));
        jLabel12.setText("Nº");

        jTNum.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jTRazSoc, javax.swing.GroupLayout.DEFAULT_SIZE, 302, Short.MAX_VALUE))
                .addGap(130, 130, 130))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jTCNPJ, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel11)
                    .addComponent(jTInsEst, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(183, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel10)
                            .addComponent(jTEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel9)
                            .addComponent(jTTel, javax.swing.GroupLayout.DEFAULT_SIZE, 92, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(77, 77, 77)
                        .addComponent(jLabel5)
                        .addGap(56, 56, 56)
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 102, Short.MAX_VALUE))
                    .addComponent(jLabel3)
                    .addComponent(jLabel6)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTCEP, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTBairro, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jCEstado, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jCUF, 0, 68, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(238, 238, 238)
                                .addComponent(jLabel8))
                            .addComponent(jTEnd, javax.swing.GroupLayout.DEFAULT_SIZE, 269, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel12)
                                .addGap(15, 15, 15))
                            .addComponent(jTNum, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(130, 130, 130))
            .addGroup(layout.createSequentialGroup()
                .addGap(144, 144, 144)
                .addComponent(jBCadastrar)
                .addContainerGap(213, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTRazSoc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTCNPJ, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel11)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTInsEst, 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(jLabel3)
                    .addComponent(jLabel12))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTEnd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTNum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jLabel5)
                    .addComponent(jLabel7)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTCEP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTBairro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jCEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jCUF, 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(jLabel10)
                    .addComponent(jLabel9))
                .addGap(7, 7, 7)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTTel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jBCadastrar)
                .addContainerGap(19, Short.MAX_VALUE))
        );

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

private void jBCadastrarActionPerformed(java.awt.event.ActionEvent evt) {                                         
Fornecedor f = new Fornecedor();
f.setRazao_Social(jTRazSoc.getText());
f.setCNPJ(jTCNPJ.getText());
f.setIns_Estadual(jTInsEst.getText());    
f.setEnd(jTEnd.getText()+" "+jTNum);
f.setCEP(jTCEP.getText());    
f.setBairro(jTBairro.getText());
f.setEstado(String.valueOf(jCEstado.getSelectedItem()));
f.setUF(String.valueOf(jCUF.getSelectedItem()));
f.setEmail(jTEmail.getText());
f.setTel(jTTel.getText());
f.Cadastrar_Fornecedor();

}                                        

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(Cadatro_Fornecedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Cadatro_Fornecedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Cadatro_Fornecedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Cadatro_Fornecedor.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 Cadatro_Fornecedor().setVisible(true);
                
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jBCadastrar;
    private javax.swing.JComboBox jCEstado;
    private javax.swing.JComboBox jCUF;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JTextField jTBairro;
    private javax.swing.JTextField jTCEP;
    private javax.swing.JTextField jTCNPJ;
    private javax.swing.JTextField jTEmail;
    private javax.swing.JTextField jTEnd;
    private javax.swing.JTextField jTInsEst;
    private javax.swing.JTextField jTNum;
    private javax.swing.JTextField jTRazSoc;
    private javax.swing.JTextField jTTel;
    // End of variables declaration
public void PreencherCombo(){
    Fornecedor f = new Fornecedor();
    f.ConsultarEstado();
        try {
            while (resultado.next()){
                jCEstado.addItem(resultado.getString("Nome_est"));
            }
        } catch (SQLException ex) {
            Logger.getLogger(Cadatro_Fornecedor.class.getName()).log(Level.SEVERE, null, ex);
        }
}
}
GOSTEI 0
Douglas Eric

Douglas Eric

05/01/2012

Você não fez como eu falei! Vou fazer aqui o que você deveria ter feito, e quem sabe, funcionado:
try {  
            while (resultado.next()){  
                jCEstado.addItem(resultado.getString(?)); // No lugar do ?, coloque o número correspondente a coluna onde são salvos os Estados
                jCEstado.updateUI; // Para atualizar o JComboBox
            }  
        } catch (SQLException ex) {  
            Logger.getLogger(Cadatro_Fornecedor.class.getName()).log(Level.SEVERE, null, ex);  
        }
não sei como está a Estrutura da sua tabela, mas você tem uma tabela só para Estados? se sim a sua instrução SQL deve ser:
select * from nome_da_sua_tabela
se não a sua instrução SQL deve ser:
select coluna_dos_estados from nome_da_sua_tabela
GOSTEI 0
Douglas Eric

Douglas Eric

05/01/2012

mano eu fiz e não foi será que tem que colocar o codigo em outro lugar?
GOSTEI 0
Kelvin Bianchi

Kelvin Bianchi

05/01/2012

[quote="wingaspar"]mano eu fiz e não foi será que tem que colocar o codigo em outro lugar?
Então, eu pedi para você postar as classes que estão utilizando o Banco, mas você postou só a metade de uma, a interface não importa neste momento! Ahh... mais uma coisa! Posta a classe como está com as atualizações que eu pedi, quero ver como ficou.
GOSTEI 0
Douglas Eric

Douglas Eric

05/01/2012

jFrame o codigo ta no final dela
package Telas;

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import jne.*;

public class Cadatro_Fornecedor extends javax.swing.JFrame {
 ResultSet resultado;
   
    public Cadatro_Fornecedor() {
        initComponents();
        setLocationRelativeTo(null);
    }      

    @SuppressWarnings("unchecked")
    
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jBCadastrar = new javax.swing.JButton();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jTCNPJ = new javax.swing.JTextField();
        jTInsEst = new javax.swing.JTextField();
        jTRazSoc = new javax.swing.JTextField();
        jTEnd = new javax.swing.JTextField();
        jTBairro = new javax.swing.JTextField();
        jCEstado = new javax.swing.JComboBox();
        jCUF = new javax.swing.JComboBox();
        jTEmail = new javax.swing.JTextField();
        jTTel = new javax.swing.JTextField();
        jTCEP = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        jTNum = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cadastro de Fornecedor");

        jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 11));
        jLabel1.setText("CNPJ");

        jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 11));
        jLabel2.setText("Razão Social");

        jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 11));
        jLabel3.setText("Endereço");

        jLabel5.setFont(new java.awt.Font("Times New Roman", 1, 11));
        jLabel5.setText("Bairro");

        jLabel6.setFont(new java.awt.Font("Times New Roman", 1, 11));
        jLabel6.setText("CEP");

        jLabel7.setFont(new java.awt.Font("Times New Roman", 1, 11));
        jLabel7.setText("Estado");

        jLabel8.setFont(new java.awt.Font("Times New Roman", 1, 11));
        jLabel8.setText("UF");

        jBCadastrar.setFont(new java.awt.Font("Times New Roman", 1, 11)); // NOI18N
        jBCadastrar.setText("Cadastrar");
        jBCadastrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBCadastrarActionPerformed(evt);
            }
        });

        jLabel9.setFont(new java.awt.Font("Times New Roman", 1, 11));
        jLabel9.setText("Telefone");

        jLabel10.setFont(new java.awt.Font("Times New Roman", 1, 11));
        jLabel10.setText("E-Mail");

        jLabel11.setFont(new java.awt.Font("Times New Roman", 1, 11));
        jLabel11.setText("Ins. Estadual");

        jTCNPJ.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jTInsEst.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jTRazSoc.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jTEnd.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jTBairro.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jCEstado.setFont(new java.awt.Font("Times New Roman", 1, 11)); // NOI18N
        jCEstado.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jCUF.setFont(new java.awt.Font("Times New Roman", 1, 11));
        jCUF.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jTEmail.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jTTel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jTCEP.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel12.setFont(new java.awt.Font("Times New Roman", 1, 11));
        jLabel12.setText("Nº");

        jTNum.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jTRazSoc, javax.swing.GroupLayout.DEFAULT_SIZE, 302, Short.MAX_VALUE))
                .addGap(130, 130, 130))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jTCNPJ, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel11)
                    .addComponent(jTInsEst, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(183, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel10)
                            .addComponent(jTEmail, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel9)
                            .addComponent(jTTel, javax.swing.GroupLayout.DEFAULT_SIZE, 92, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(77, 77, 77)
                        .addComponent(jLabel5)
                        .addGap(56, 56, 56)
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 102, Short.MAX_VALUE))
                    .addComponent(jLabel3)
                    .addComponent(jLabel6)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jTCEP, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTBairro, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jCEstado, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jCUF, 0, 68, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(238, 238, 238)
                                .addComponent(jLabel8))
                            .addComponent(jTEnd, javax.swing.GroupLayout.DEFAULT_SIZE, 269, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel12)
                                .addGap(15, 15, 15))
                            .addComponent(jTNum, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addGap(130, 130, 130))
            .addGroup(layout.createSequentialGroup()
                .addGap(144, 144, 144)
                .addComponent(jBCadastrar)
                .addContainerGap(213, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTRazSoc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTCNPJ, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel11)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTInsEst, 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(jLabel3)
                    .addComponent(jLabel12))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTEnd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTNum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel6)
                    .addComponent(jLabel5)
                    .addComponent(jLabel7)
                    .addComponent(jLabel8))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTCEP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTBairro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jCEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jCUF, 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(jLabel10)
                    .addComponent(jLabel9))
                .addGap(7, 7, 7)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTTel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jBCadastrar)
                .addContainerGap(19, Short.MAX_VALUE))
        );

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

private void jBCadastrarActionPerformed(java.awt.event.ActionEvent evt) {                                         
Fornecedor f = new Fornecedor();
f.setRazao_Social(jTRazSoc.getText());
f.setCNPJ(jTCNPJ.getText());
f.setIns_Estadual(jTInsEst.getText());    
f.setEnd(jTEnd.getText()+" "+jTNum);
f.setCEP(jTCEP.getText());    
f.setBairro(jTBairro.getText());
f.setEstado(String.valueOf(jCEstado.getSelectedItem()));
f.setUF(String.valueOf(jCUF.getSelectedItem()));
f.setEmail(jTEmail.getText());
f.setTel(jTTel.getText());
f.Cadastrar_Fornecedor();

}                                        

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(Cadatro_Fornecedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Cadatro_Fornecedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Cadatro_Fornecedor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Cadatro_Fornecedor.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 Cadatro_Fornecedor().setVisible(true);
                
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jBCadastrar;
    private javax.swing.JComboBox jCEstado;
    private javax.swing.JComboBox jCUF;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JTextField jTBairro;
    private javax.swing.JTextField jTCEP;
    private javax.swing.JTextField jTCNPJ;
    private javax.swing.JTextField jTEmail;
    private javax.swing.JTextField jTEnd;
    private javax.swing.JTextField jTInsEst;
    private javax.swing.JTextField jTNum;
    private javax.swing.JTextField jTRazSoc;
    private javax.swing.JTextField jTTel;
    // End of variables declaration
public void PreencherCombo(){
    Fornecedor f = new Fornecedor();
    f.ConsultarEstado();
        try {
            while (resultado.next()){
                jCEstado.addItem(resultado.getString(1));
                jCEstado.updateUI();
            }
        } catch (SQLException ex) {
            Logger.getLogger(Cadatro_Fornecedor.class.getName()).log(Level.SEVERE, null, ex);
        }
}
}
Classe fornecedor
package jne;

import java.sql.*;
import javax.swing.*;

public class Fornecedor {
private String Razao_Social,CNPJ,Ins_Estadual,
        End,CEP,Bairro,Estado,UF,Email,Tel;
ResultSet resultado;

    public String getRazao_Social() {
        return Razao_Social;
    }
    public void setRazao_Social(String Razao_Social) {
        this.Razao_Social = Razao_Social;
    }
    public String getCNPJ() {
        return CNPJ;
    }
    public void setCNPJ(String CNPJ) {
        this.CNPJ = CNPJ;
    }
    public String getIns_Estadual() {
        return Ins_Estadual;
    }
    public void setIns_Estadual(String Ins_Estadual) {
        this.Ins_Estadual = Ins_Estadual;
    }
    public String getEnd() {
        return End;
    }
    public void setEnd(String End) {
        this.End = End;
    }
    public String getCEP() {
        return CEP;
    }
    public void setCEP(String CEP) {
        this.CEP = CEP;
    }
    public String getBairro() {
        return Bairro;
    }
    public void setBairro(String Bairro) {
        this.Bairro = Bairro;
    }
    public String getEstado() {
        return Estado;
    }
    public void setEstado(String Estado) {
        this.Estado = Estado;
    }
    public String getUF() {
        return UF;
    }
    public void setUF(String UF) {
        this.UF = UF;
    }
    public String getEmail() {
        return Email;
    }
    public void setEmail(String Email) {
        this.Email = Email;
    }
    public String getTel() {
        return Tel;
    }
    public void setTel(String Tel) {
        this.Tel = Tel;
    }
    
     public void Cadastrar_Fornecedor(){
        Connection conexao = Banco.getConexao();        
        try {
            Statement stmt = conexao.createStatement();
            String sql = "insert into fornecedor (Razao_Social,CNPJ,Ins_Estadual,End,CEP,Bairro,Estado,UF,Email,Tel) values "
                    + "('"+Razao_Social+"','"+CNPJ+"','"+Ins_Estadual+"','"+End+"','"+CEP+"','"+Bairro+"','"+Estado+"','"+UF+"','"+Email+"','"+Tel+"')";
            stmt.execute(sql);
            JOptionPane.showMessageDialog(null, "Cadastro realizado com sucesso !");
        } catch (Exception erro) {
            System.out.println("Erro ao cadastrar Fornecedor: "+erro);
        }
       }
     
       public ResultSet ConsultarEstado(){
        Connection conexao = Banco.getConexao();
        try {            
            Statement stmt = conexao.createStatement();
            String sql = "select * from estado ";                    
            resultado = stmt.executeQuery(sql);            
            } catch (Exception erro) {
            System.out.println(" Erro ao consultar estado: "+erro);
        }
     return resultado;   
    }
}
Classe banco
package jne;
import java.sql.Connection;
import java.sql.DriverManager;
public class Banco {
      public static Connection getConexao() {
        Connection conexao = null;
        try {
            //driver que será utilizado
            Class.forName("com.mysql.jdbc.Driver");
            //cria um objeto de conexao com um banco especificado no caminho...
            conexao = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/jne", "root", "123");
        } catch (Exception erro) {
            System.out.println(erro);
        }
        return conexao;
    }
}
Qual que eu postei metade que eu posto denovo foi mal! e o banco ta certo fiz a consulta pelo mysql e trouxe todos os estados cadastrados
GOSTEI 0
Douglas Eric

Douglas Eric

05/01/2012

O importante é que já sabemos que o problema não está no SQL! Acho que para resolver isto, teremos de usar uma Lista ([b]List[/b]), achei um tópico aqui no fórum mesmo, que talvez possa lhe ajudar, dê uma lida nele e tente compreendê-lo e botá-lo em prática! Qualquer coisa, só voltar aqui e perguntar! [i]Link:[/i] [url]http://javafree.uol.com.br/topic-884450-JComboBox-para-consulta-no-banco-de-dados.html[/url]
GOSTEI 0
Douglas Eric

Douglas Eric

05/01/2012

valeu foi ver esse tópico
GOSTEI 0
Kelvin Bianchi

Kelvin Bianchi

05/01/2012

Para fazer a lista seria mais ou menos assim:
public ArrayList findAll(){
// PreparedStatement e outros...
ArrayList lista = new ArrayList();
while(rs.next()){
    lista.add(rs.getString(?)); // Onde no lugar de ? coloque a posição da coluna correspondente aos Estados
}
return lista;
}
e no seu [b]JComboBox[/b]:
JComboBox seuComboBox = new JComboBox(lista);
[i][Códigos não testados em nenhuma IDE!!][/i] Ahh.. e bote o [i]updateUI[/i] fora do [i]while[/i]!
GOSTEI 0
André Pereira

André Pereira

05/01/2012

[quote="wingaspar"][...]
public ResultSet ConsultarEstado(){
        Connection conexao = Banco.getConexao();
        try {            
            Statement stmt = conexao.createStatement();
            String sql = "select * from estado";                    
            resultado = stmt.executeQuery(sql);            
            } catch (Exception erro) {
            System.out.println(" Erro ao consultar estado: "+erro);
        }
     return resultado;   
    }
Presumo que este metodo esta dentro da classe Fornecedor... [quote="wingaspar"]
public void PreencherCombo(){   
    [b]Fornecedor f = new Fornecedor();   
    f.ConsultarEstado[/b]   
        try {   
            while (resultado.next()){   
                jCEstado.addItem(resultado.getString("Nome_est"));   
            }   
        } catch (SQLException ex) {   
            Logger.getLogger(Cadatro_Fornecedor.class.getName()).log(Level.SEVERE, null, ex);   
        }   
}
Sendo isso, este metodo retorna um ResultSet, do qual vc não atribui a nenhuma variavel... acho que nem esta entrando no loop while... Para testar o while ficaria assim:
Fornecedor f = new Fornecedor();   
Resultset resultado = f.ConsultarEstado   
       while (resultado.next()){
          //codigo dentro do while...
       }
Tenta alterar essa parte e posta se deu certo... Não testado!!!
GOSTEI 0
Windson Amorim

Windson Amorim

05/01/2012

Valeu cara acho que era isso mesmo coloquei esse codigo na pós-inicialização da combo e deu certo
Fornecedor f = new Fornecedor();
    resultado=f.ConsultarEstado();
    System.out.println(resultado);
           try {
            while (resultado.next()){
                jCEstado.addItem(resultado.getString(1));
                jCEstado.updateUI();
            }
        } catch (SQLException ex) {
            Logger.getLogger(Cadatro_Fornecedor.class.getName()).log(Level.SEVERE, null, ex);
        }
Agradeço a todos que me ajudaram!!!
GOSTEI 0
Windson Amorim

Windson Amorim

05/01/2012

[quote="wingaspar"]Valeu cara acho que era isso mesmo coloquei esse codigo na pós-inicialização da combo e deu certo
Fornecedor f = new Fornecedor();
    resultado=f.ConsultarEstado();
    System.out.println(resultado);
           try {
            while (resultado.next()){
                jCEstado.addItem(resultado.getString(1));
                jCEstado.updateUI();
            }
        } catch (SQLException ex) {
            Logger.getLogger(Cadatro_Fornecedor.class.getName()).log(Level.SEVERE, null, ex);
        }
Agradeço a todos que me ajudaram!!!
estranho não ter dado erro de compilação....
GOSTEI 0
Douglas Eric

Douglas Eric

05/01/2012

[quote="simu"][quote="wingaspar"]Valeu cara acho que era isso mesmo coloquei esse codigo na pós-inicialização da combo e deu certo
Fornecedor f = new Fornecedor();
    resultado=f.ConsultarEstado();
    System.out.println(resultado);
           try {
            while (resultado.next()){
                jCEstado.addItem(resultado.getString(1));
                jCEstado.updateUI();
            }
        } catch (SQLException ex) {
            Logger.getLogger(Cadatro_Fornecedor.class.getName()).log(Level.SEVERE, null, ex);
        }
Agradeço a todos que me ajudaram!!!
estranho não ter dado erro de compilação....
[img]http://javafree.uol.com.br/files_user/files/B/61/B4/netbeans.jpg[/img] Mas eu não achei o erro :/ Sou péssimo naqueles "jogo do sete erros"
GOSTEI 0
Kelvin Bianchi

Kelvin Bianchi

05/01/2012

[quote="simu"][quote="wingaspar"]Valeu cara acho que era isso mesmo coloquei esse codigo na pós-inicialização da combo e deu certo
Fornecedor f = new Fornecedor();
    resultado=f.ConsultarEstado();
    System.out.println(resultado);
           try {
            while (resultado.next()){
                jCEstado.addItem(resultado.getString(1));
                jCEstado.updateUI();
            }
        } catch (SQLException ex) {
            Logger.getLogger(Cadatro_Fornecedor.class.getName()).log(Level.SEVERE, null, ex);
        }
Agradeço a todos que me ajudaram!!!
estranho não ter dado erro de compilação....
Por isto eu não gosto da paleta do NetBeans, pode ser mais rápido, mais confio mais, colocando os componentes na mão mesmo! Ali no [b]Fornecedor f = new Fornecedor();[/b] eu acharia melhor, passar por parâmetro do método, assim:
public void PreencherCombo(Fornecedor f) // ....
GOSTEI 0
Douglas Eric

Douglas Eric

05/01/2012

[quote="kbianchi"][quote="simu"][quote="wingaspar"]Valeu cara acho que era isso mesmo coloquei esse codigo na pós-inicialização da combo e deu certo
Fornecedor f = new Fornecedor();
    resultado=f.ConsultarEstado();
    System.out.println(resultado);
           try {
            while (resultado.next()){
                jCEstado.addItem(resultado.getString(1));
                jCEstado.updateUI();
            }
        } catch (SQLException ex) {
            Logger.getLogger(Cadatro_Fornecedor.class.getName()).log(Level.SEVERE, null, ex);
        }
Agradeço a todos que me ajudaram!!!
estranho não ter dado erro de compilação....
Por isto eu não gosto da paleta do NetBeans, pode ser mais rápido, mais confio mais, colocando os componentes na mão mesmo! Ali no [b]Fornecedor f = new Fornecedor();[/b] eu acharia melhor, passar por parâmetro do método, assim:
public void PreencherCombo(Fornecedor f) // ....
Por isso que não tinha certeza se realmente era isso, por q o correto seria da erro de compilação. @kbianchi, tbm acho que seria melhor passar o objeto do parametro.
GOSTEI 0
Douglas Eric

Douglas Eric

05/01/2012

qual erro??? D:
GOSTEI 0
Kelvin Bianchi

Kelvin Bianchi

05/01/2012

[quote="sekkuar"]qual erro??? D:
Eu também ainda não vi o "erro" que tanto falam. Para mim, o "erro" era algo como organização (ou algo do tipo) de ter criado o objeto da classe dentro do método, invés de passar o objeto por parâmetro.
GOSTEI 0
Douglas Eric

Douglas Eric

05/01/2012

[quote="kbianchi"][quote="sekkuar"]qual erro??? D:
Eu também ainda não vi o "erro" que tanto falam. Para mim, o "erro" era algo como organização (ou algo do tipo) de ter criado o objeto da classe dentro do método, invés de passar o objeto por parâmetro.
Como assim??? O erro é que ele esta usando uma variavel que não existe... A não ser que ele declarou uma variavel do tipo ResultSet com o mesmo nome (resultado), isso não daria erro de compilação e sim de execução, pois estaria trazendo um resultset diferente do que ele realmente quer.
GOSTEI 0
Douglas Eric

Douglas Eric

05/01/2012

[quote="D3z40"][quote="kbianchi"][quote="sekkuar"]qual erro??? D:
Eu também ainda não vi o "erro" que tanto falam. Para mim, o "erro" era algo como organização (ou algo do tipo) de ter criado o objeto da classe dentro do método, invés de passar o objeto por parâmetro.
Como assim??? O erro é que ele esta usando uma variavel que não existe... A não ser que ele declarou uma variavel do tipo ResultSet com o mesmo nome (resultado), isso não daria erro de compilação e sim de execução, pois estaria trazendo um resultset diferente do que ele realmente quer. declarou sim, no inicio da classe
public class Cadatro_Fornecedor extends javax.swing.JFrame {  
 ResultSet resultado;  
//...
GOSTEI 0
Kelvin Bianchi

Kelvin Bianchi

05/01/2012

[quote="D3z40"][quote="kbianchi"][quote="sekkuar"]qual erro??? D:
Eu também ainda não vi o "erro" que tanto falam. Para mim, o "erro" era algo como organização (ou algo do tipo) de ter criado o objeto da classe dentro do método, invés de passar o objeto por parâmetro.
Como assim??? O erro é que ele esta usando uma variavel que não existe... A não ser que ele declarou uma variavel do tipo ResultSet com o mesmo nome (resultado), isso não daria erro de compilação e sim de execução, pois estaria trazendo um resultset diferente do que ele realmente quer. No início da classe ele declarou a variável "resultado".
GOSTEI 0
Douglas Eric

Douglas Eric

05/01/2012

[quote="sekkuar"][quote="D3z40"][quote="kbianchi"][quote="sekkuar"]qual erro??? D:
Eu também ainda não vi o "erro" que tanto falam. Para mim, o "erro" era algo como organização (ou algo do tipo) de ter criado o objeto da classe dentro do método, invés de passar o objeto por parâmetro.
Como assim??? O erro é que ele esta usando uma variavel que não existe... A não ser que ele declarou uma variavel do tipo ResultSet com o mesmo nome (resultado), isso não daria erro de compilação e sim de execução, pois estaria trazendo um resultset diferente do que ele realmente quer. declarou sim, no inicio da classe
public class Cadatro_Fornecedor extends javax.swing.JFrame {  
 ResultSet resultado;  
//...
Blz (não olhei o codigo no detalhe), então isso entra naquela questão do erro de execução, ele criou um metodo para retornar um resultSet, porem usa outro resultSet, acho que é pior ainda, apesar de nunca ter esquecido de declarar variavel ate hoje, acho que é mais facil esquecer de declarar uma variavel do que criar um metodo que retorna um resultSet e usar outro.
GOSTEI 0
Douglas Eric

Douglas Eric

05/01/2012

[quote="D3z40"] Blz (não olhei o codigo no detalhe), então isso entra naquela questão do erro de execução, ele criou um metodo para retornar um resultSet, porem usa outro resultSet, acho que é pior ainda, apesar de nunca ter esquecido de declarar variavel ate hoje, acho que é mais facil esquecer de declarar uma variavel do que criar um metodo que retorna um resultSet e usar outro.
Não consigo entender o que está errado ainda. A variável ResultSet existe, ela está como um atributo; Dentro do método, ele puxa o objeto de conexão, cria um Statement, faz a consulta, e salva ela no dito resultset; Com o resultset carregado, ele cria um loop e popula a combobox. Claro, ter o resultset como atributo é inútil e desperdício. Mas não vejo ele "usando" e nem "retornando" nenhum outro resultset, apenas o da consulta que ele gerou. claro, o código dele está longe de ser um bom código, mas funciona.
GOSTEI 0
Douglas Eric

Douglas Eric

05/01/2012

[quote="sekkuar"][quote="D3z40"] Blz (não olhei o codigo no detalhe), então isso entra naquela questão do erro de execução, ele criou um metodo para retornar um resultSet, porem usa outro resultSet, acho que é pior ainda, apesar de nunca ter esquecido de declarar variavel ate hoje, acho que é mais facil esquecer de declarar uma variavel do que criar um metodo que retorna um resultSet e usar outro.
Não consigo entender o que está errado ainda. A variável ResultSet existe, ela está como um atributo; Dentro do método, ele puxa o objeto de conexão, cria um Statement, faz a consulta, e salva ela no dito resultset; Com o resultset carregado, ele cria um loop e popula a combobox. Claro, ter o resultset como atributo é inútil e desperdício. Mas não vejo ele "usando" e nem "retornando" nenhum outro resultset, apenas o da consulta que ele gerou. claro, o código dele está longe de ser um bom código, mas funciona.
O metodo que ele usa para retornar o ResultSet é este:
public ResultSet ConsultarEstado(){   
        Connection conexao = Banco.getConexao();   
        try {               
            Statement stmt = conexao.createStatement();   
            String sql = "select * from estado";                       
            resultado = stmt.executeQuery(sql);               
            } catch (Exception erro) {   
            System.out.println(" Erro ao consultar estado: "+erro);   
        }   
     return resultado;      
}
Este metodo esta dentro da classe Fornecedor. E no main ele estava fazendo isso...
    ResultSet resultado;
    public void PreencherCombo(){   
    Fornecedor f = new Fornecedor();   
    f.ConsultarEstado   
        try {   
            while (resultado.next()){   
                jCEstado.addItem(resultado.getString("Nome_est"));   
            }   
        } catch (SQLException ex) {   
            Logger.getLogger(Cadatro_Fornecedor.class.getName()).log(Level.SEVERE, null, ex);   
        }   
}
Ele chama o metodo ConsultarEstado que retorna um ResultSet, mas não atribui esse retorno a nenhuma variavel, por isso que passei para ele fazer isso:
resultado = f.ConsultarEstado
Dessa forma que ele estava fazendo nem entrava no loop while, a variavel resultado que ele estava passando para o loop tinha o valor de null... Foi falta de atençao dele mesmo...
GOSTEI 0
Douglas Eric

Douglas Eric

05/01/2012

[quote="D3z40"] Ele chama o metodo ConsultarEstado que retorna um ResultSet, mas não atribui esse retorno a nenhuma variavel, por isso que passei para ele fazer isso:
resultado = f.ConsultarEstado
Dessa forma que ele estava fazendo nem entrava no loop while, a variavel resultado que ele estava passando para o loop tinha o valor de null... Foi falta de atençao dele mesmo...
Mas calma lá. Você está confundindo as coisas, eu me refiro a este post do simu [quote="simu"][quote="wingaspar"]Valeu cara acho que era isso mesmo coloquei esse codigo na pós-inicialização da combo e deu certo
Fornecedor f = new Fornecedor();
    resultado=f.ConsultarEstado();
    System.out.println(resultado);
           try {
            while (resultado.next()){
                jCEstado.addItem(resultado.getString(1));
                jCEstado.updateUI();
            }
        } catch (SQLException ex) {
            Logger.getLogger(Cadatro_Fornecedor.class.getName()).log(Level.SEVERE, null, ex);
        }
Agradeço a todos que me ajudaram!!!
estranho não ter dado erro de compilação.... Aqui ele atribuiu certo. Simu disse que tem erro de compilação, é esse erro que eu não acho. Nesse código ele já tinha arrumado o
resultado=f.ConsultarEstado()
de que você está falando.
GOSTEI 0
Douglas Eric

Douglas Eric

05/01/2012

[quote="sekkuar"][quote="D3z40"] Ele chama o metodo ConsultarEstado que retorna um ResultSet, mas não atribui esse retorno a nenhuma variavel, por isso que passei para ele fazer isso:
resultado = f.ConsultarEstado
Dessa forma que ele estava fazendo nem entrava no loop while, a variavel resultado que ele estava passando para o loop tinha o valor de null... Foi falta de atençao dele mesmo...
Mas calma lá. Você está confundindo as coisas, eu me refiro a este post do simu [quote="simu"][quote="wingaspar"]Valeu cara acho que era isso mesmo coloquei esse codigo na pós-inicialização da combo e deu certo
Fornecedor f = new Fornecedor();
    resultado=f.ConsultarEstado();
    System.out.println(resultado);
           try {
            while (resultado.next()){
                jCEstado.addItem(resultado.getString(1));
                jCEstado.updateUI();
            }
        } catch (SQLException ex) {
            Logger.getLogger(Cadatro_Fornecedor.class.getName()).log(Level.SEVERE, null, ex);
        }
Agradeço a todos que me ajudaram!!!
estranho não ter dado erro de compilação.... Aqui ele atribuiu certo. Simu disse que tem erro de compilação, é esse erro que eu não acho. Nesse código ele já tinha arrumado o
resultado=f.ConsultarEstado()
de que você está falando. :hauhau: :hauhau: :hauhau: Pensei que vc estava falando do erro antes dele corrigir, acho que o simu estava se referindo antes de corrigir.. assim com eu, pelo menos foi assim que entendi...
GOSTEI 0
POSTAR