Olá pessoal, estou desenvolvendo um projeto pequeno, uma agenda. Estou desenvolvendo utilizando 3 camadas, no formulário de cadastro do Contato, eu coloquei um jComboBox para que a pessoa possa escolher a categoria deste contato quando for cadastrá-lo, porém não estou conseguindo adicionar as categorias que estão no banco de dados no jComboBox, já tentei várias maneiras, mas não consegui de forma alguma. Segue abaixo o meu código:
Beans:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package beans;
/**
*
* @author MaYcKoN
*/
public class Categoria {
private int idcategoria;
private String descricao;
/**
* @return the idcategoria
*/
public int getIdcategoria() {
return idcategoria;
}
/**
* @param idcategoria the idcategoria to set
*/
public void setIdcategoria(int idcategoria) {
this.idcategoria = idcategoria;
}
/**
* @return the descricao
*/
public String getDescricao() {
return descricao;
}
/**
* @param descricao the descricao to set
*/
public void setDescricao(String descricao) {
this.descricao = descricao;
}
}
DAO:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
import beans.Categoria;
import java.sql.*;
import java.sql.PreparedStatement;
import javax.swing.JOptionPane;
import java.util.List;
import java.util.LinkedList;
public class CategoriaDAO extends Conexao {
public void inserir(Categoria categoria) throws ClassNotFoundException, SQLException{
String sql = "INSERT INTO categoria(descricao)VALUES(?)";
PreparedStatement ps = getPreparedStatement(sql);
ps.setString(1, categoria.getDescricao());
ps.execute();
ps.close();
}
public void atualizar(Categoria categoria) throws ClassNotFoundException, SQLException{
String sql = "UPDATE categoria SET descricao=? where idcategoria=?";
PreparedStatement ps = getPreparedStatement(sql);
ps.setInt(1, categoria.getIdcategoria());
ps.setString(2, categoria.getDescricao());
ps.execute();
ps.close();
}
public void excluir(Categoria categoria) throws ClassNotFoundException, SQLException{
String sql = "DELETE FROM categoria WHERE idcategoria=?";
PreparedStatement ps = getPreparedStatement(sql);
ps.setInt(1, categoria.getIdcategoria());
ps.execute();
ps.close();
}
public Categoria getCategoria(int id) throws ClassNotFoundException, SQLException{
Categoria categ = new Categoria();
String sql = "SELECT*FROM categoria WHERE idcategoria=?";
PreparedStatement ps = getPreparedStatement(sql);
ps.setInt(1, id);
ResultSet rs = ps.executeQuery();
if(rs.next()){
categ.setIdcategoria(rs.getInt("idcategoria"));
categ.setDescricao(rs.getString("descricao"));
}
ps.close();
return categ;
}
public List<Categoria> pesquisar(String descricao) throws ClassNotFoundException, SQLException{
List<Categoria> categorias = new LinkedList<Categoria>();
String sql = "SELECT * FROM categoria WHERE descricao LIKE ? ORDER BY descricao";
PreparedStatement ps = getPreparedStatement(sql);
ps.setString(1, descricao+"%");
ResultSet rs = ps.executeQuery();
Categoria categ;
while(rs.next()){
categ = new Categoria();
categ.setIdcategoria(rs.getInt("idcategoria"));
categ.setDescricao(rs.getString("descricao"));
categorias.add(categ);
}
rs.close();
ps.close();
return categorias;
}
public List<Categoria> listar() throws ClassNotFoundException, SQLException{
List<Categoria> categorias = new LinkedList<Categoria>();
// Categoria categ = new Categoria();
String sql = "SELECT * FROM categoria";
ResultSet rs = getStatement().executeQuery(sql);
while(rs.next()){
Categoria categ = new Categoria();
categ.setIdcategoria(rs.getInt("idcategoria"));
categ.setDescricao(rs.getString("descricao"));
categorias.add(categ);
}
rs.close();
return categorias;
}
}
Negócio:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Negocio;
/**
*
* @author MaYcKoN
*/
import beans.Contato;
import DAO.ContatoDAO;
import DAO.CategoriaDAO;
import beans.Categoria;
import java.sql.SQLException;
import java.util.*;
import javax.swing.JOptionPane;
public class NegocioCadContato {
public boolean cadastrarContato(ArrayList<Contato> contato){
return true;
}
public List pegaCategoria() throws ClassNotFoundException, SQLException{
CategoriaDAO categ = new CategoriaDAO();
return categ.listar();
}
}
Interface:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* CadastrarContato.java
*
* Created on 13/06/2011, 10:16:21
*/
package Views;
/**
*
* @author MaYcKoN
*/
import java.sql.SQLException;
import java.util.*;
import Negocio.NegocioCadContato;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
public class CadastrarContato extends javax.swing.JFrame {
/** Creates new form CadastrarContato */
public CadastrarContato() {
initComponents();
setLocationRelativeTo(null);
jLblPreencher.setVisible(!jLblPreencher.isVisible());
}
/** 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">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jTxtNome = new javax.swing.JTextField();
jTxtTelefone = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jTxtCelular = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jTxtEndereco = new javax.swing.JTextField();
jTxtCidade = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jTxtBairro = new javax.swing.JTextField();
jTxtDataNasc = new javax.swing.JTextField();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jTxtEmail = new javax.swing.JTextField();
jTxtObservacao = new javax.swing.JTextField();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jCmbBoxCateg = new javax.swing.JComboBox();
jButton1 = new javax.swing.JButton();
jLblPreencher = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
setTitle("Cadastrar Contatos");
jLabel1.setText("Nome");
jLabel2.setText("Telefone");
jLabel3.setText("Celular");
jLabel4.setText("Endereco");
jTxtEndereco.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jTxtEnderecoActionPerformed(evt);
}
});
jLabel5.setText("Cidade");
jLabel6.setText("Bairro");
jLabel7.setText("Data de Nascimento");
jLabel8.setText("Email");
jLabel9.setText("Observação");
jLabel10.setText("Categoria deste contato");
jCmbBoxCateg.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jCmbBoxCategMouseClicked(evt);
}
});
jCmbBoxCateg.addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentShown(java.awt.event.ComponentEvent evt) {
jCmbBoxCategComponentShown(evt);
}
});
jCmbBoxCateg.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jCmbBoxCategActionPerformed(evt);
}
});
jButton1.setText("Cadastrar");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLblPreencher.setForeground(new java.awt.Color(255, 51, 51));
jLblPreencher.setText("Os campos marcados com * devem ser obrigatórios");
jLabel11.setText("*");
jLabel13.setText("*");
org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.addContainerGap()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(jLabel1)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jTxtNome, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 507, Short.MAX_VALUE))
.add(jLabel12))
.add(2, 2, 2)
.add(jLabel11)
.addContainerGap())
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
.add(layout.createSequentialGroup()
.add(jLabel2)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jTxtTelefone, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 158, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.add(jLabel3)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jTxtCelular, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 158, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.add(1, 1, 1)
.add(jLabel13, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 102, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createSequentialGroup()
.add(jLabel4)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jTxtEndereco, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 487, Short.MAX_VALUE))
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
.add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
.add(jLabel6)
.add(18, 18, 18)
.add(jTxtBairro))
.add(org.jdesktop.layout.GroupLayout.LEADING, layout.createSequentialGroup()
.add(jLabel5)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jTxtCidade, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 259, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.add(layout.createSequentialGroup()
.add(jLabel8)
.add(18, 18, 18)
.add(jTxtEmail, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 252, Short.MAX_VALUE)
.add(250, 250, 250))
.add(layout.createSequentialGroup()
.add(jLabel10)
.add(18, 18, 18)
.add(jCmbBoxCateg, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 216, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createSequentialGroup()
.add(jLabel9)
.add(18, 18, 18)
.add(jTxtObservacao, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 443, Short.MAX_VALUE)
.add(20, 20, 20)))
.add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
.add(jButton1)
.add(213, 213, 213))
.add(layout.createSequentialGroup()
.add(jLabel7)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jTxtDataNasc, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 103, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.add(28, 28, 28))))
.add(layout.createSequentialGroup()
.add(126, 126, 126)
.add(jLblPreencher)
.addContainerGap(151, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(8, 8, 8)
.add(jLblPreencher)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
.add(layout.createSequentialGroup()
.add(jLabel11)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jLabel12))
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel1)
.add(jTxtNome, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.add(jLabel12)
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel10)
.add(jCmbBoxCateg, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel7)
.add(jTxtDataNasc, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel2)
.add(jTxtTelefone, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jTxtCelular, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
.add(jLabel3)
.add(jLabel13))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel4)
.add(jTxtEndereco, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel5)
.add(jTxtCidade, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel6)
.add(jTxtBairro, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel8)
.add(jTxtEmail, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
.add(jLabel9)
.add(jTxtObservacao, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 105, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
.add(jButton1)
.add(45, 45, 45))
);
jTxtNome.getAccessibleContext().setAccessibleName("");
pack();
}// </editor-fold>
private void jTxtEnderecoActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
if(jTxtNome.getText().equals("") || jTxtCelular.getText().equals("")){
jLblPreencher.setVisible(true); // torna a label visivel. Aviso para preencher os campos obrigatórios.
}
else{
ArrayList dadosContato = new ArrayList();
dadosContato.add(jTxtNome.getText());
}
}
private void jCmbBoxCategMouseClicked(java.awt.event.MouseEvent evt) {
jCmbBoxCateg.addItem("desgraça");
}
private void jCmbBoxCategActionPerformed(java.awt.event.ActionEvent evt) {
DefaultComboBoxModel model = new DefaultComboBoxModel();
NegocioCadContato obj = new NegocioCadContato();
try {
model.addElement(obj.pegaCategoria());
jCmbBoxCateg = new JComboBox(model);
} catch (ClassNotFoundException ex) {
Logger.getLogger(CadastrarContato.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(CadastrarContato.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void jCmbBoxCategComponentShown(java.awt.event.ComponentEvent evt) {
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CadastrarContato().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JComboBox jCmbBoxCateg;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
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.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JLabel jLblPreencher;
private javax.swing.JTextField jTxtBairro;
private javax.swing.JTextField jTxtCelular;
private javax.swing.JTextField jTxtCidade;
private javax.swing.JTextField jTxtDataNasc;
private javax.swing.JTextField jTxtEmail;
private javax.swing.JTextField jTxtEndereco;
private javax.swing.JTextField jTxtNome;
private javax.swing.JTextField jTxtObservacao;
private javax.swing.JTextField jTxtTelefone;
// End of variables declaration
}
Galera, testei de todo jeito, mas não consigo colocar minha lista de categorias neste JComboBox.