Como mostrar os dados de uma tabela do BD em um ComboBox
Olá,
Tenho uma tabela de grupos de produtos e gostaria de mostrar os grupos cadastrados em um combobox. Alguém tem algum exemplo?
Obrigado.
Ronaldo Albertini
Curtidas 0
Respostas
Everton Barros
09/04/2009
Exemplo? agora to sem tempo mais [url=http://www.javafree.org/javabb/viewtopic.jbb?t=869138&jComboBox]aqui[/url] vai uma dica.
GOSTEI 0
Ronaldo Albertini
09/04/2009
VAleu pela dica.
Obrigado
GOSTEI 0
Calvin Rankin
09/04/2009
//INICIO - Carregar lista para a ComboBox
try{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/bancodedados", "root","senha");
Statement stm= con.createStatement();
String sql ="select * from nomedatabela;";
com.mysql.jdbc.ResultSet rs = (com.mysql.jdbc.ResultSet) stm.executeQuery(sql);
while (rs.next()){
jCcomboBox.addItem(rs.getInt("Codigo"));
}
}catch (SQLException ex){
jArea1.append("Ocorreu um erro ao carregar o ComboBox");
}
//FIM - Carregar lista para a ComboBox GOSTEI 0
Jefferson
09/04/2009
Boa Noite, sou novo por aqui e estava com o problema de carregar os dados da base de dados MySQL para o JComboBox e o código do Calvin Rankin está correto, funcionou...
GOSTEI 0
Bruno Marinho
09/04/2009
Entao galera primeiramente boa noite a td's. Sou novo aki e iniciante em java. Eu fiz uma aplicação na qual qnd a msm fosse carregada, ela exibisse o dados vindo do banco de dados. Eu ate consegui puxar uns dados do banco, so q qnd eu carrego a aplicação a combo nao carrega os dados automaticamente, pra carrega eu tenho q selecionar algum item da combo e dps qnd eu volto na combo os dados estao la, e td vez q eu clico em uma opção ele duplica a informação na combo. Queria q alguem me ajudasse a resolver esse problema, queria q a combo fosse carrega com dados do banco assim q a aplicação fosse carregada e ao selecionar um item da combo q nao duplicasse os itens.
Agradeço desde ja tds.
Vou postar o codigo do programa
//Codigo da Conexao
package Fonte;
import java.sql.*;
public class Conexao {
public Connection connection=null;
private final String DRIVER = "org.gjt.mm.mysql.Driver";
private final String URL = "jdbc:mysql://localhost/cadcliente";
private final String LOGIN = "root";
private final String SENHA = "admin";
public boolean getConnection(){
try{
Class.forName(DRIVER);
connection = DriverManager.getConnection(URL, LOGIN, SENHA);
System.out.println("Conectou1");
return true;
}
catch(ClassNotFoundException erro){
System.out.println("Driver nao encontrado " + erro.toString());
return false;
}
catch(SQLException erro){
System.out.println("Falha ao conectar " + erro.toString());
return false;
}
}
public void close(){
try{
connection.close();
System.out.println("Desconectou");
}
catch(SQLException erro){
}
}
}
//Codigo do Cliente
package Fonte;
public class Cliente {
private String matricula, nome, telefone, sexo, cpf;
public String getMatricula(){
return matricula;
}
public void setMatricula(String matricula){
this.matricula=matricula;
}
public String getNome(){
return nome;
}
public void setNome(String nome){
this.nome=nome;
}
public String getTelefone(){
return telefone;
}
public void setTelefone(String telefone){
this.telefone=telefone;
}
public String getSexo(){
return sexo;
}
public void setSexo(String sexo){
this.sexo=sexo;
}
public String getCpf(){
return cpf;
}
public void setCpf(String cpf){
this.cpf=cpf;
}
}
//codigo cliente DAO
package Fonte;
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class ClienteDAO {
public Cliente cliente;
public Conexao bd;
private PreparedStatement statement;
public static ResultSet resultset;
private String sql;
public static final byte inclusao = 1;
public static final byte alteracao = 2;
public static final byte exclusao = 3;
public ClienteDAO(){
bd = new Conexao();
cliente = new Cliente();
}
public ResultSet consultaMatricula(){
sql = "SELECT matricula, nome FROM cliente";
try{
statement = bd.connection.prepareStatement(sql);
resultset = statement.executeQuery();
}
catch(Exception erro){
JOptionPane.showMessageDialog(null,"Erro ao consultar" +erro.toString());
}
return resultset;
}
//Codigo da Aplicação(Formulario)
package Fonte;
/
public class cadCliente extends javax.swing.JFrame {
ClienteDAO cli;
public cadCliente() {
initComponents();
cli = new ClienteDAO();
if(! cli.bd.getConnection()){
JOptionPane.showMessageDialog(null,"Falha na conexao, o sistema sera fechado!");
System.exit(0);
}
}
public void preencherCombo(){
ResultSet rs;
rs=cli.consultaMatricula();
try {
//cbMatricula.removeAllItems();
while(rs.next()){
String matricula = rs.getString(1);
String nome = rs.getString(2);
cbMatricula.addItem(matricula +" : "+ nome);
cbMatricula.updateUI();
}
} catch (SQLException ex) {
Logger.getLogger(cadCliente.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void cbMatriculaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbMatriculaActionPerformed
// TODO add your handling code here:
preencherCombo();
}//GEN-LAST:event_cbMatriculaActionPerformed
public static void main(String args[]){
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
try {
new cadCliente().setVisible(true);
} catch (Exception ex) {
Logger.getLogger(cadCliente.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btConsultar;
private javax.swing.JButton btEditar;
private javax.swing.JButton btExcluir;
private javax.swing.JButton btGerarPdf;
private javax.swing.JButton btSalvar;
private javax.swing.JButton btVerificar;
private javax.swing.JComboBox cbMatricula;
private javax.swing.JComboBox cbSexo;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JPanel jPanel1;
private javax.swing.JFormattedTextField tfCpf;
private javax.swing.JTextField txDigiteMatricula;
private javax.swing.JTextField txMatricula;
private javax.swing.JTextField txNome;
private javax.swing.JTextField txTelefone;
// End of variables declaration//GEN-END:variables
}
peço a ajuda de todos, quem puder ajuda eu agradeço, pq tsou iniciante e to aki pra aprender e quem sbe dps ensinar tbm, obrigado e abçs
Read more: http://javafree.uol.com.br/topic-3239-ComboBox.html#ixzz2AW8OTXm3
GOSTEI 0