Olá marcos tudo bem?
Primeiramente gostaria de agradecer-lhe a resposta ;),
Mas entao brother quando eu coloco o codigo que você me flw até da certo, mas quando eu vou passando por cada item no banco ele vai adicionando ex:
Suponha que em minha tabela eu tenha cadastrado 2 itens : 01, São José dos Campos, SP
02, Niteroi, RJ
usando o codigo
cb_uf.addItem(con_cidade.resultset.getString("uf"));
cada vez que eu passo pelo codigo ele vai adicionando mais uma uf ex:
01 - SJC, Sao Paulo (o programa adiciona SP)
02 - Niteroi, RJ
ai eu volto de novo
01 SJC, São Paulo,
na combobox ficaria as opções SP, RJ, SP.
E nao era para cadastrar itens com o mesmo nome duas vezes ;)
Segue baixo o meu codigo completo ;)
mas meu erro está a partir da linha 407
Caslo alguns de vocês possam me dar uma força ;)
Atenciosamte,
Leo
package cadastros;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import utilitarios.conexao;
public class cad_cidade extends javax.swing.JFrame {
int navega = 0;// variável para sabermos me qual botao foi clicado
conexao con_cidade; // variavel do banco
public cad_cidade() {
initComponents();
// conectar banco
con_cidade = new conexao();
con_cidade.conecta();
con_cidade.executeSql("select * from cidade");
try{
con_cidade.resultset.first();
mostrar_dados();
}catch(SQLException erro){
JOptionPane.showMessageDialog(null,"Não localizou dados "+ erro);
}
}
/** 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.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
tf_codigo = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
tf_nome = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
cb_uf = new javax.swing.JComboBox();
botao_primeiro = new javax.swing.JButton();
botao_anterior = new javax.swing.JButton();
botao_proximo = new javax.swing.JButton();
botao_ultimo = new javax.swing.JButton();
botao_gravar = new javax.swing.JButton();
botao_inserir = new javax.swing.JButton();
botao_excluir = new javax.swing.JButton();
botao_alterar = new javax.swing.JButton();
jLabel5 = new javax.swing.JLabel();
tf_Pesquisa = new javax.swing.JTextField();
cb_pesquisa = new javax.swing.JComboBox();
botao_novo = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Manutenção do Cadastro de Cidades");
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18));
jLabel1.setForeground(new java.awt.Color(102, 255, 204));
jLabel1.setText("Manutenção do Cadastro de Cidades");
jLabel2.setText("Código :");
tf_codigo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tf_codigoActionPerformed(evt);
}
});
jLabel3.setText("Nome :");
jLabel4.setText("UF :");
cb_uf.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "item1", "item2", "item3" }));
cb_uf.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cb_ufActionPerformed(evt);
}
});
botao_primeiro.setText("<<");
botao_primeiro.setToolTipText("Vai para o primeiro registro");
botao_primeiro.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botao_primeiroActionPerformed(evt);
}
});
botao_anterior.setText("<");
botao_anterior.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botao_anteriorActionPerformed(evt);
}
});
botao_proximo.setText(">");
botao_proximo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botao_proximoActionPerformed(evt);
}
});
botao_ultimo.setText(">>");
botao_ultimo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botao_ultimoActionPerformed(evt);
}
});
botao_gravar.setText("Gravar");
botao_gravar.setToolTipText("Grava o registro");
botao_gravar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botao_gravarActionPerformed(evt);
}
});
botao_inserir.setText("Inserir");
botao_excluir.setText("Excluir");
botao_excluir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botao_excluirActionPerformed(evt);
}
});
botao_alterar.setText("Alterar");
botao_alterar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botao_alterarActionPerformed(evt);
}
});
jLabel5.setText("Pesquisar: ");
tf_Pesquisa.setToolTipText("Digite as iniciais da Cidade para localizar");
cb_pesquisa.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
cb_pesquisa.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cb_pesquisaActionPerformed(evt);
}
});
botao_novo.setText("Novo");
botao_novo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
botao_novoActionPerformed(evt);
}
});
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(24, 24, 24)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(botao_primeiro)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel3)
.addComponent(jLabel4)
.addComponent(jLabel5))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(tf_nome)
.addComponent(tf_codigo, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(tf_Pesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(14, 14, 14)
.addComponent(botao_anterior)
.addGap(24, 24, 24)
.addComponent(botao_proximo))
.addGroup(layout.createSequentialGroup()
.addGap(17, 17, 17)
.addComponent(cb_uf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(botao_ultimo)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(22, 22, 22)
.addComponent(botao_novo)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(botao_gravar)
.addGap(18, 18, 18)
.addComponent(botao_inserir)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(botao_excluir)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(botao_alterar))
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cb_pesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(165, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 325, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(187, 187, 187))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(24, 24, 24)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(tf_Pesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(cb_pesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(38, 38, 38)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(tf_codigo, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(27, 27, 27)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(tf_nome, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(37, 37, 37)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4)
.addComponent(cb_uf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(botao_primeiro)
.addComponent(botao_anterior)
.addComponent(botao_ultimo)
.addComponent(botao_proximo)
.addComponent(botao_alterar)
.addComponent(botao_excluir)
.addComponent(botao_inserir)
.addComponent(botao_gravar)
.addComponent(botao_novo))
.addContainerGap(77, Short.MAX_VALUE))
);
java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
setBounds((screenSize.width-693)/2, (screenSize.height-417)/2, 693, 417);
}// </editor-fold>//GEN-END:initComponents
private void tf_codigoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tf_codigoActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_tf_codigoActionPerformed
private void botao_primeiroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_primeiroActionPerformed
try{
con_cidade.resultset.first();
mostrar_dados();
}catch(SQLException erro){
JOptionPane.showMessageDialog(null,"Não foi possível ir para o primeiro registro "+ erro);
}
}//GEN-LAST:event_botao_primeiroActionPerformed
private void cb_pesquisaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cb_pesquisaActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cb_pesquisaActionPerformed
private void cb_ufActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cb_ufActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_cb_ufActionPerformed
private void botao_proximoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_proximoActionPerformed
try{
con_cidade.resultset.next();
mostrar_dados();
navega = 2;
}catch(SQLException erro){
JOptionPane.showMessageDialog(null,"Não foi possível ir para o próximo registro "+ erro);
}
}//GEN-LAST:event_botao_proximoActionPerformed
private void botao_ultimoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_ultimoActionPerformed
try{
con_cidade.resultset.last();
mostrar_dados();
}catch(SQLException erro){
JOptionPane.showMessageDialog(null,"Não foi possível ir para o ultimo registro "+ erro);
}
}//GEN-LAST:event_botao_ultimoActionPerformed
private void botao_anteriorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_anteriorActionPerformed
try{
con_cidade.resultset.previous();
mostrar_dados();
navega = 1;
}catch(SQLException erro){
JOptionPane.showMessageDialog(null,"Não foi pode ir para o registro anterior "+ erro);
}
}//GEN-LAST:event_botao_anteriorActionPerformed
private void botao_novoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_novoActionPerformed
tf_codigo.setText("");
tf_nome.setText("");
cb_uf.setSelectedItem("RS");
tf_nome.requestFocus();
tf_codigo.setEditable(false);
}//GEN-LAST:event_botao_novoActionPerformed
private void botao_gravarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_gravarActionPerformed
// código para gravar os dados no Banco de Dados
try{
// insert int cidade (nome,uf) values ('Carazinho','RS');
String sqlinsert = "insert into cidade(nome,uf) values ('"+
tf_nome.getText()+" ','"+
cb_uf.getSelectedItem()+" ')";
con_cidade.statement.executeUpdate(sqlinsert);
JOptionPane.showMessageDialog(null,"Gravação realizada com sucesso ");
// atualiza o ResultSet
//con_cidade.resultset = con_cidade.statement.executeQuery("Select * from cidade");
con_cidade.executeSql("select * from cidade");
con_cidade.resultset.first();// posiciona no primeiro registro
mostrar_dados();// irá chamar a função em que irá mostrar os dados
}catch (SQLException erro){
}
}//GEN-LAST:event_botao_gravarActionPerformed
private void botao_excluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_excluirActionPerformed
try{
String sql = "select * from cidade Where codigo ="+tf_codigo.getText();
con_cidade.executeSql(sql);
con_cidade.resultset.first();
String nome = "Deletar a Cidade: "+ con_cidade.resultset.getString("nome")+ " ?";
int opcao_escolhida = JOptionPane.showConfirmDialog(null, nome, " Exclusão ",JOptionPane.YES_NO_OPTION);
if (opcao_escolhida == JOptionPane.YES_OPTION){
sql = "DELETE FROM cidade Where codigo ="+tf_codigo.getText();
int conseguiu_excluir = con_cidade.statement.executeUpdate(sql);
if(conseguiu_excluir == 1){
JOptionPane.showMessageDialog(null, "Exclusão realizada com sucesso");
// atualiza o Resultset
con_cidade.executeSql("Select * from cidade");
con_cidade.resultset.first();// posiciona no primeiro registro
mostrar_dados();// irá chamar a função em que irá mostrar os dados no form
}
}
else
return;
}catch (SQLException erro){
JOptionPane.showMessageDialog(null, "Erro ao tentar excluir o registro..."+ erro);
}
}//GEN-LAST:event_botao_excluirActionPerformed
private void botao_alterarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botao_alterarActionPerformed
// código para alterar dados no banco de dados
try{
String sql = "UPDATE cidade SET nome='"+tf_nome.getText()+"',"+
"uf = '"+cb_uf.getSelectedItem()+"' where codigo = "+tf_codigo.getText();
con_cidade.statement.executeUpdate(sql);
JOptionPane.showMessageDialog(null, "Alteração realizado com sucesso!");
// atualiza o ResultSet
con_cidade.executeSql("Select * from cidade");
con_cidade.resultset.next();// poisiciona no primeiro registro
mostrar_dados();// irá chamar a função em que ira mostrar os dados no formulario
}catch(SQLException erro){
JOptionPane.showMessageDialog(null,"Erro ao tentar alterar o registro..." +erro);
}
}//GEN-LAST:event_botao_alterarActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new cad_cidade().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton botao_alterar;
private javax.swing.JButton botao_anterior;
private javax.swing.JButton botao_excluir;
private javax.swing.JButton botao_gravar;
private javax.swing.JButton botao_inserir;
private javax.swing.JButton botao_novo;
private javax.swing.JButton botao_primeiro;
private javax.swing.JButton botao_proximo;
private javax.swing.JButton botao_ultimo;
private javax.swing.JComboBox cb_pesquisa;
private javax.swing.JComboBox cb_uf;
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.JTextField tf_Pesquisa;
private javax.swing.JTextField tf_codigo;
private javax.swing.JTextField tf_nome;
// End of variables declaration//GEN-END:variables
public void mostrar_dados(){
try{
tf_codigo.setText(con_cidade.resultset.getString("codigo"));
tf_nome.setText(con_cidade.resultset.getString("nome"));
cb_uf.setSelectedItem(con_cidade.resultset.getString("uf"));// não consegue pegar os dados da unidade federativa no campo uf da tabela cidade no banco alguem sabe //porque?
}catch(SQLException erro){
if (navega ==1)
JOptionPane.showMessageDialog(null,"Olha você ja esta no primeiro registro");
else if (navega == 2)
JOptionPane.showMessageDialog(null,"Olha você ja esta no ultimo registro");
else
JOptionPane.showMessageDialog(null,"Não localizou dados "+ erro);
navega = 0;
}
}
}