Carregar informações do banco de dados para um JComboBox?

Pessoal to precisando de um ajuda! como eu faço para carregar informações do meu Banco de Dados para um jcombobox ?

Exemplo tenho uma tela de cadastro de clientes quero carregar as cidades cadastradas que tenho o meu BD no jcombobox que tem nessa tela…

Alguem sabe ??
:?: :?: :?: :?: :?: :?: :?: :?:

Ferramenta de Desenvovimento: Netbeans 6.8
Banco de Dados: Postgres 9.0 Beta 4

flw
abraço :wink:
agurdando respostas…

Olá!

Você já consegue fazer a consulta no banco?

Se consegue, pegue o retorno dentro de um foreach e vá adicionando no combo box.

OK!
valeu cara…
ma svo poderia especificar um pouco mais
?

Primeiramente fazemos a classe de conexão.

[code]/*

  • To change this template, choose Tools | Templates
  • and open the template in the editor.
    */

package Conexao.bd;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
*

  • @Thiago Gonçalves Fonseca
    */
    public class Conexao {

    final private String driver = “com.mysql.jdbc.Driver”;
    final private String url = “jdbc:mysql://localhost:3306/supercredjava”;
    final private String usuario = “root”;
    final private String senha = “root”;
    private Connection conexao;
    public Statement statement;
    public ResultSet resultset;

    public boolean conecta() {
    boolean result = true;
    try {
    Class.forName(driver);
    conexao = DriverManager.getConnection(url, usuario, senha);
    System.out.println(“CONECTOU”);
    } catch (ClassNotFoundException Driver) {
    System.out.println("DRIVER NÃ?O LOCALIZADO " + Driver);
    result = false;
    } catch (SQLException Fonte) {
    System.out.println("DEU ERRO NA CONEXÃ?O " + “COM A FONTE DE DADOS” + Fonte);
    result = false;
    }
    return result;
    }

    public void desconecta() {
    boolean result = true;
    try {
    conexao.close();
    System.out.println(“Conexão com banco FECHADA”);
    } catch (SQLException fecha) {
    System.out.println("NÃ?O FOI POSSIVEL " + "FECHAR O BANCO DE DADOS " + fecha);
    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) {
    System.out.println("executeSQL: NÃ?O FOI POSSIVEL " + “EXECUTAR O COMANDO sql " + sqlex + " , o sql passado foi: \n” + sql);
    }
    }

    public void executeUpdate(String sqlupdate) {
    try {
    statement = conexao.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
    statement.executeUpdate(sqlupdate);
    } catch (SQLException ex) {
    ex.printStackTrace();
    }
    }

}
[/code]

Vamos a consulta.

/*
 * Principal.java
 *
 * Created on 23/06/2010, 23:43:21
 * Projeto criado originalmente no Netbeans 6.8
 */

package ConsultaClientecombo.view;

import Conexao.bd.Conexao;
import java.awt.event.ItemEvent;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

/**
 *
 * @Thiago Gonçalves Fonseca
 * Consulta Clientes

 *
 */
public class Principal extends javax.swing.JFrame {
    private Conexao con_cli = new Conexao();
    private String codcli = null;

    /** Construtor desta classe */
    public Principal() {
        initComponents();
        //método responsável por inserir os clientes do BD no JComboBox
        setComboClientes();
        //Metodo para mudar a aparencia de alguns itens
        setAparencia();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jComboBox1 = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jTextField2 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Clientes: ");

        jComboBox1.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBox1ItemStateChanged(evt);
            }
        });

        jLabel2.setText("Codigo cliente: ");

        jTextField1.setEnabled(false);

        jLabel3.setText("Nome Cliente:");

        jButton1.setText("Gravar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Sair");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 10));
        jLabel4.setText("Supercred Promotora de Vendas Ltda");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 234, Short.MAX_VALUE))
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 297, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButton1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jButton2))
                            .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 233, Short.MAX_VALUE))))
                .addGap(69, 69, 69))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(255, Short.MAX_VALUE)
                .addComponent(jLabel4))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jComboBox1, 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(jLabel2)
                    .addComponent(jTextField1, 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(jLabel3)
                    .addComponent(jTextField2, 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(jButton1)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel4))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_jComboBox1ItemStateChanged
        if (evt.getStateChange() == ItemEvent.SELECTED ){//jComboBox1.getItemCount() > -1) {
            System.out.println("Item Selecionado: " + jComboBox1.getSelectedItem());
            getDadosCliente();
        } 
    }//GEN-LAST:event_jComboBox1ItemStateChanged

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        String sqlupdate = "UPDATE cliente SET nome_cliente='" + jTextField2.getText() + "' WHERE cod_cliente=" + jTextField1.getText();
        con_cli.conecta();
        con_cli.executeUpdate(sqlupdate);
        con_cli.desconecta();
        setComboClientes();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration//GEN-END:variables

    private void setComboClientes(){
        jComboBox1.removeAllItems();
        con_cli.conecta();
        con_cli.executeSQL("SELECT * FROM cliente ORDER BY nome_cliente");
        try {
            while (con_cli.resultset.next()){
                jComboBox1.addItem(con_cli.resultset.getString("cod_cliente") + " - " + con_cli.resultset.getString("nome_cliente"));
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        con_cli.desconecta();
    }

    private void setLookAndFeel() {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
            SwingUtilities.updateComponentTreeUI(this);
            this.pack();
        } catch (ClassNotFoundException ex) {
            JOptionPane.showMessageDialog(this, ex);
        } catch (InstantiationException ex) {
            JOptionPane.showMessageDialog(this, ex);
        } catch (IllegalAccessException ex) {
            JOptionPane.showMessageDialog(this, ex);
        } catch (UnsupportedLookAndFeelException ex) {
            JOptionPane.showMessageDialog(this, ex);
        }
    }

    private void getDadosCliente() {
        
        //O método split separa a string selecionada do jComboBox por um separador, no caso " - "
        //Abaixo, criei um array que recebe do método split os itens em cada posição
        String itensSemSeparador[] = jComboBox1.getSelectedItem().toString().split(" - ");
        //pega o primeiro valor do array e exibe no jTextField
        jTextField1.setText(itensSemSeparador[0]);
        //pega o segundo valor do array e exibe no jTextField
        jTextField2.setText(itensSemSeparador[1]);
    }

    private void setAparencia() {
        //método que troca o lookAndFell deste JFrame
        //LookAndFeel é a aparencia dos botões e janelas usada pelo gerenciador de janelas swing
        setLookAndFeel();
        //Modifica o título da janela
        setTitle("Consulta Clientes(Alteração))");
        //Modifica a dica para o botão quando passa o mouse sobre ele
        jButton1.setToolTipText("Altere o nome do cliente selecionado na no box acima e clique aqui(alterar) para alterar!");
    }
}

Sim!

Se voce já tem a conexão, basicamente o que você precisa está ai no código que nosso amigo postou.

Para ser mais especifico, voce precisa de algo assim:

//Executa o select
con_cli.executeSQL("SELECT * FROM cliente ORDER BY nome_cliente");   
        try {   
            //Itera pelos itens e vai adicionando no combobox
            while (con_cli.resultset.next()){   
                jComboBox1.addItem(con_cli.resultset.getString("nome_cliente"));   
            }   
        } catch (SQLException ex) {   
            ex.printStackTrace();   
        }   

Se você não tem a classe de conexão, de uma analisada no código do THIAGOANALISTA que já está pronto.

abraço!

Use este código para retornar no seu combo.

jComboBox1.removeAllItems(); con_cli.conecta(); con_cli.executeSQL("SELECT * FROM cliente ORDER BY nome_cliente"); try { while (con_cli.resultset.next()){ jComboBox1.addItem(con_cli.resultset.getString("cod_cliente") + " - " + con_cli.resultset.getString("nome_cliente")); } } catch (SQLException ex) { ex.printStackTrace(); } con_cli.desconecta(); }

Blz rapariada vc são de +
vou testar no meu projeto
abraço
vlw pela resposta

Desculpa ai cara…
mas quer dizer que este código vai em um evento do Jcombobox ?
por que a tela ja tenho feita

   1. jComboBox1.removeAllItems();    
   2.     con_cli.conecta();    
   3.    con_cli.executeSQL("SELECT * FROM cliente ORDER BY nome_cliente");    
   4.     try {    
   5.         while (con_cli.resultset.next()){    
   6.             jComboBox1.addItem(con_cli.resultset.getString("cod_cliente") + " - " + con_cli.resultset.getString("nome_cliente"));    
   7.         }    
   8.     } catch (SQLException ex) {    
   9.         ex.printStackTrace();    
  10.     }    
  11.     con_cli.desconecta();    
  12. }    

Desculp a falta de conhecimento…
tamo aqui pra aprender né!
flw

Criando o combobox

 jComboBox1 = new javax.swing.JComboBox();  [quote]

adicionando Listner

ComboBox1.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { jComboBox1ItemStateChanged(evt); } });

Recuperando os dados

private void setComboClientes(){ jComboBox1.removeAllItems(); con_cli.conecta(); con_cli.executeSQL("SELECT * FROM cliente ORDER BY nome_cliente"); try { while (con_cli.resultset.next()){ jComboBox1.addItem(con_cli.resultset.getString("cod_cliente") + " - " + con_cli.resultset.getString("nome_cliente")); } } catch (SQLException ex) { ex.printStackTrace(); } con_cli.desconecta(); }

Execute os dois códigos acima postados e estude o código;