Enviado em 03/09/2017 - 12:06h
Olá
package Controle;
import Conexao.ConectaBanco;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import modelo.ModeloBairro;
/**
*
* @author brainiac
*/
public class ControleBairro {
ConectaBanco conex = new ConectaBanco();
ConectaBanco conexPesq = new ConectaBanco();
String cidade = null;
int codCid = 0;
// inserir dados no BD
public void gravar(ModeloBairro obj) {
conex.conexao();
try {
conex.executaSQL("SELECT * FROM cidade WHERE nome_cidade='"+obj.getCidade()+"'");
conex.rs.first();
codCid = conex.rs.getInt("id_cidade");
PreparedStatement pst = conex.con.prepareStatement("INSERT INTO bairro (nome_bairro, id_cidade) VALUES(?, ?)");
pst.setString(1, obj.getNome());
pst.setInt(2, codCid);
pst.execute();
JOptionPane.showMessageDialog(null, "Inserido com sucesso pela Camada Controle");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Não Inserido pela Camada Controle!"+ex);
}
conex.desconecta();
}
// Botão Primeiro
public ModeloBairro primeiro() {
conex.conexao();
ModeloBairro modBairro = new ModeloBairro();
conexPesq.conexao();
conex.executaSQL("SELECT * FROM bairro");
try {
conex.rs.first();
conexPesq.executaSQL("SELECT * FROM cidade WHERE id_cidade=" +conex.rs.getInt("id_cidade"));
conexPesq.rs.first();
cidade = conexPesq.rs.getString("nome_cidade");
modBairro.setCod(conex.rs.getInt("id_bairro"));
modBairro.setNome(conex.rs.getString("nome_bairro"));
modBairro.setCidade(cidade);
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "erro ao mostrar dados na Camada Controle!"+ex);
}
conex.desconecta();
conexPesq.desconecta();
return modBairro;
}
// Botão anterior
public ModeloBairro anterior() {
conex.conexao();
ModeloBairro modBairro = new ModeloBairro();
conexPesq.conexao();
try {
conex.rs.previous();
conexPesq.executaSQL("SELECT * FROM cidade WHERE id_cidade=" +conex.rs.getInt("id_cidade"));
conexPesq.rs.first();
cidade = conexPesq.rs.getString("nome_cidade");
modBairro.setCod(conex.rs.getInt("id_bairro"));
modBairro.setNome(conex.rs.getString("nome_bairro"));
modBairro.setCidade(cidade);
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "erro ao mostrar dados na Camada Controle!"+ex);
}
conexPesq.desconecta();
return modBairro;
}
// botão próximo
public ModeloBairro proximo() {
conex.conexao();
ModeloBairro modBairro = new ModeloBairro();
conexPesq.conexao();
try {
conex.rs.next();
conexPesq.executaSQL("SELECT * FROM cidade WHERE id_cidade=" +conex.rs.getInt("id_cidade"));
conexPesq.rs.first();
cidade = conexPesq.rs.getString("nome_cidade");
modBairro.setCod(conex.rs.getInt("id_bairro"));
modBairro.setNome(conex.rs.getString("nome_bairro"));
modBairro.setCidade(cidade);
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "erro ao mostrar dados na Camada Controle!"+ex);
}
conexPesq.desconecta();
return modBairro;
}
// botão último
public ModeloBairro ultimo() {
conex.conexao();
ModeloBairro modBairro = new ModeloBairro();
conexPesq.conexao();
conex.executaSQL("SELECT * FROM bairro");
try {
conex.rs.last();
conexPesq.executaSQL("SELECT * FROM cidade WHERE id_cidade=" +conex.rs.getInt("id_cidade"));
conexPesq.rs.first();
cidade = conexPesq.rs.getString("nome_cidade");
modBairro.setCod(conex.rs.getInt("id_bairro"));
modBairro.setNome(conex.rs.getString("nome_bairro"));
modBairro.setCidade(cidade);
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "erro ao mostrar dados na Camada Controle!"+ex);
}
conex.desconecta();
conexPesq.desconecta();
return modBairro;
}
//Alterar dado no BD
//Alterar dado no BD
public void editar(ModeloBairro obj) {
conex.conexao();
conexPesq.conexao();
//JOptionPane.showMessageDialog(null, obj.getCod_estado());
try {
conexPesq.executaSQL("SELECT * FROM cidade WHERE nome_cidade="+obj.getNome());
conexPesq.rs.first();
codCid= conex.rs.getInt("id_cidade");
PreparedStatement pst= conex.con.prepareStatement("UPDATE bairro SET nome_bairro=?, id_cidade=? WHERE id_bairro=?");
pst.setString(1, obj.getNome());
pst.setInt(2, codCid);
pst.setInt(3, obj.getCod());
pst.execute();
JOptionPane.showMessageDialog(null, "Dados Editados com sucesso pela Camada Controle!");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Dados não Editados com sucesso pela Camada Controle!");
}
conex.desconecta();
conexPesq.desconecta();
}
public void excluir(ModeloBairro obj) {
conex.conexao();
conexPesq.conexao();
//JOptionPane.showMessageDialog(null, obj.getCod_estado());
try {
PreparedStatement pst= conex.con.prepareStatement("DELETE FROM bairro WHERE id_bairro=?");
pst.setInt(1, obj.getCod());
pst.execute();
JOptionPane.showMessageDialog(null, "Dados Excluídos com sucesso pela Camada Controle!");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Dados não Excluídos com sucesso pela Camada Controle!");
}
conex.desconecta();
conexPesq.desconecta();
}
}// fim
package modelo;
/**
*
* @author brainiac
*/
public class ModeloBairro {
private int cod;
private String nome;
private String cidade;
public int getCod() {
return cod;
}
public void setCod(int cod) {
this.cod = cod;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCidade() {
return cidade;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
}
package visao;
import Conexao.ConectaBanco;
import Controle.ControleBairro;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import modelo.ModeloBairro;
import modelo.ModeloTabela;
/**
*
* @author brainiac
*/
public class FrmBairros extends javax.swing.JFrame {
ConectaBanco conectaBairro = new ConectaBanco();
ModeloBairro modeloBairro = new ModeloBairro();
ControleBairro controleBairro = new ControleBairro();
int flag = 1;
/**
* Creates new form FrmBairos
*/
public FrmBairros() {
initComponents();
conectaBairro.conexao();
btnNovo.setEnabled(true);
preencherTabela("SELECT * FROM bairro INNER JOIN cidade ON bairro.id_cidade = cidade.id_cidade");
atualizarCombo();
}
/**
* 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() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
txtCod = new javax.swing.JTextField();
txtNome = new javax.swing.JTextField();
jComboBoxCidade = new javax.swing.JComboBox<>();
jLabel3 = new javax.swing.JLabel();
btnAdd = new javax.swing.JButton();
btnNovo = new javax.swing.JButton();
btnSalvar = new javax.swing.JButton();
btnAlterar = new javax.swing.JButton();
btnDelete = new javax.swing.JButton();
btnPrimeiro = new javax.swing.JButton();
btnProximo = new javax.swing.JButton();
btnAnterior = new javax.swing.JButton();
btnUltimo = new javax.swing.JButton();
btnCancelar = new javax.swing.JButton();
btnSair = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTableBairro = new javax.swing.JTable();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Cadastro de Bairros");
jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Formulário Cadastro de Bairros", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Arial Black", 1, 14), new java.awt.Color(255, 102, 51))); // NOI18N
jPanel1.setEnabled(false);
jLabel1.setText("Código:");
jLabel2.setText("Nome:");
txtCod.setEnabled(false);
txtNome.setToolTipText("Nome do Bairro");
jComboBoxCidade.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
jLabel3.setText("Cidade:");
btnAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/city.png"))); // NOI18N
btnAdd.setToolTipText("Adicionar outra Cidade, add another city");
btnAdd.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAddActionPerformed(evt);
}
});
btnNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/adicionar.png"))); // NOI18N
btnNovo.setToolTipText("Novo, new");
btnNovo.setEnabled(false);
btnNovo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnNovoActionPerformed(evt);
}
});
btnSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/gravar.png"))); // NOI18N
btnSalvar.setToolTipText("Salvar, save");
btnSalvar.setEnabled(false);
btnSalvar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSalvarActionPerformed(evt);
}
});
btnAlterar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/editar.png"))); // NOI18N
btnAlterar.setToolTipText("Editar, alterar, edit");
btnAlterar.setEnabled(false);
btnAlterar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAlterarActionPerformed(evt);
}
});
btnDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/deletar.png"))); // NOI18N
btnDelete.setToolTipText("Deletar, apagar, delete, erase");
btnDelete.setEnabled(false);
btnDelete.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDeleteActionPerformed(evt);
}
});
btnPrimeiro.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/resultset_first.png"))); // NOI18N
btnPrimeiro.setToolTipText("Primeiro, first");
btnPrimeiro.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnPrimeiroActionPerformed(evt);
}
});
btnProximo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/resultset_next.png"))); // NOI18N
btnProximo.setToolTipText("Próximo, next");
btnProximo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnProximoActionPerformed(evt);
}
});
btnAnterior.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/resultset_previous.png"))); // NOI18N
btnAnterior.setToolTipText("Anterior, previous");
btnAnterior.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAnteriorActionPerformed(evt);
}
});
btnUltimo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/resultset_last.png"))); // NOI18N
btnUltimo.setToolTipText("Último, last");
btnUltimo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnUltimoActionPerformed(evt);
}
});
btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/terminate-512.png"))); // NOI18N
btnCancelar.setToolTipText("Cancelar, Cancel");
btnCancelar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCancelarActionPerformed(evt);
}
});
btnSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagens/bot_sair.png"))); // NOI18N
btnSair.setToolTipText("Sair, exit");
btnSair.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSairActionPerformed(evt);
}
});
jTableBairro.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{},
{},
{},
{}
},
new String [] {
}
));
jScrollPane1.setViewportView(jTableBairro);
jLabel4.setFont(new java.awt.Font("Arial", 0, 8)); // NOI18N
jLabel4.setText("Adiciona outra Cidade:");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(429, 429, 429)
.addComponent(jLabel4)
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jComboBoxCidade, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtCod, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, 329, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(34, 34, 34)
.addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(191, 191, 191))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 577, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(btnNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(88, 88, 88)
.addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(btnDelete, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(36, 36, 36)
.addComponent(btnPrimeiro, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(btnAnterior, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(7, 7, 7)
.addComponent(btnProximo, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnUltimo, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(90, 90, 90)
.addComponent(btnSair, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addGap(0, 0, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(27, 27, 27)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(txtCod, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jComboBoxCidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(btnAdd, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(25, 25, 25)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(btnSalvar)
.addComponent(btnNovo)
.addComponent(btnAlterar)
.addComponent(btnDelete)
.addComponent(btnPrimeiro)
.addComponent(btnUltimo)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnSair, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(btnProximo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnAnterior, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
.addGap(21, 21, 21)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 285, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(23, Short.MAX_VALUE))
);
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()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 582, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
pack();
}// </editor-fold>
public void limpar() {
txtCod.setText("");
txtNome.setText("");
}
private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {
btnNovo.setEnabled(false);
btnSalvar.setEnabled(true);
btnCancelar.setEnabled(true);
limpar();
txtNome.setEnabled(true);
}
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {
modeloBairro.setCod(Integer.parseInt(txtCod.getText()));
controleBairro.excluir(modeloBairro);
btnNovo.setEnabled(true);
btnSalvar.setEnabled(false);
btnCancelar.setEnabled(true);
limpar();
txtNome.setEnabled(false);
preencherTabela("SELECT * FROM bairro INNER JOIN cidade ON bairro.id_cidade = cidade.id_cidade");
}
private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {
if (flag == 1) { //7:43
modeloBairro.setNome(txtNome.getText());
modeloBairro.setCidade("" + jComboBoxCidade.getSelectedItem());
controleBairro.gravar(modeloBairro);
preencherTabela("SELECT FROM bairro INNER JOIN cidade ON bairro.id_cidade=cidade.id_cidade ");
} else {
modeloBairro.setNome(txtNome.getText());
modeloBairro.setCidade("" + jComboBoxCidade.getSelectedItem());
controleBairro.editar(modeloBairro);
preencherTabela("SELECT FROM bairro INNER JOIN cidade ON bairro.id_cidade=cidade.id_cidade ");
}
btnNovo.setEnabled(true);
btnSalvar.setEnabled(false);
btnCancelar.setEnabled(true);
txtNome.setEnabled(false);
jComboBoxCidade.setEnabled(true);
limpar();
}
private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {
flag = 2;
btnNovo.setEnabled(false);
btnSalvar.setEnabled(true);
btnCancelar.setEnabled(true);
txtNome.setEnabled(true);
}
private void btnPrimeiroActionPerformed(java.awt.event.ActionEvent evt) {
modeloBairro = controleBairro.primeiro();
txtCod.setText(String.valueOf(modeloBairro.getCod()));
txtNome.setText(modeloBairro.getNome());
jComboBoxCidade.setSelectedItem(modeloBairro.getCidade());
btnDelete.setEnabled(true);
btnAlterar.setEnabled(true);
btnCancelar.setEnabled(true);
}
private void btnProximoActionPerformed(java.awt.event.ActionEvent evt) {
modeloBairro = controleBairro.proximo();
txtCod.setText(String.valueOf(modeloBairro.getCod()));
txtNome.setText(modeloBairro.getNome());
jComboBoxCidade.setSelectedItem(modeloBairro.getCidade());
btnDelete.setEnabled(true);
btnAlterar.setEnabled(true);
btnCancelar.setEnabled(true);
}
private void btnAnteriorActionPerformed(java.awt.event.ActionEvent evt) {
modeloBairro = controleBairro.anterior();
txtCod.setText(String.valueOf(modeloBairro.getCod()));
txtNome.setText(modeloBairro.getNome());
jComboBoxCidade.setSelectedItem(modeloBairro.getCidade());
btnDelete.setEnabled(true);
btnAlterar.setEnabled(true);
btnCancelar.setEnabled(true);
}
private void btnUltimoActionPerformed(java.awt.event.ActionEvent evt) {
modeloBairro = controleBairro.ultimo();
txtCod.setText(String.valueOf(modeloBairro.getCod()));
txtNome.setText(modeloBairro.getNome());
jComboBoxCidade.setSelectedItem(modeloBairro.getCidade());
btnDelete.setEnabled(true);
btnAlterar.setEnabled(true);
btnCancelar.setEnabled(true);
}
private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {
btnNovo.setEnabled(true);
btnSalvar.setEnabled(false);
btnCancelar.setEnabled(true);
btnAlterar.setEnabled(false);
btnDelete.setEnabled(false);
limpar();
txtNome.setEnabled(false);
}
private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {
this.dispose();
}
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {
FrmCidades frm= new FrmCidades();
frm.setVisible(true);
atualizarCombo();
}
public void preencherTabela(String SQL) {
ArrayList dados = new ArrayList();
String[] colunas = new String[]{"ID", "Bairro", "Cidade"};
conectaBairro.executaSQL(SQL);
try {
conectaBairro.rs.first();
// Abaixo preenchendo a tabela
do {
dados.add(new Object[]{
conectaBairro.rs.getInt("id_cidade"),
conectaBairro.rs.getString("nome_bairro"),
conectaBairro.rs.getString("nome_cidade")
});
} while (conectaBairro .rs.next());
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, " Erro ao preenchar o ArrayList!\n " + ex);
}
ModeloTabela modelo = new ModeloTabela(dados, colunas);
jTableBairro.setModel(modelo);
jTableBairro.getColumnModel().getColumn(0).setPreferredWidth(40); // Width é o tamanho em pixel
jTableBairro.getColumnModel().getColumn(0).setResizable(false); // não poderá aumentar o tamanhao com o mouse
jTableBairro.getColumnModel().getColumn(1).setPreferredWidth(300);
jTableBairro.getColumnModel().getColumn(1).setResizable(false);
jTableBairro.getColumnModel().getColumn(2).setPreferredWidth(250);
jTableBairro.getColumnModel().getColumn(2).setResizable(false);
// chamando a tabela
jTableBairro.getTableHeader().setReorderingAllowed(false);
jTableBairro.setAutoResizeMode(jTableBairro.AUTO_RESIZE_OFF);
jTableBairro.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // vai poder slecionar apenas 1 eleento desta tabela
}
public void atualizarCombo() {
jComboBoxCidade.removeAllItems(); // REmove, limpa todos os itens do comboBox, para pode armazenar em seguida
try {
conectaBairro.executaSQL("SELECT * FROM cidade ORDER BY nome_cidade");
conectaBairro.rs.first(); // para preencher tabela precisa estar posicionado no primeiro registro
do {
jComboBoxCidade.addItem(conectaBairro.rs.getString("nome_cidade"));
} while (conectaBairro.rs.next());
} catch (SQLException ex) {
JOptionPane.showMessageDialog(rootPane, "Erro ao preencher ComboBox cidade!" + ex);
}
}
/**
* @param args the command line arguments
*/
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(FrmBairros.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(FrmBairros.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(FrmBairros.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(FrmBairros.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FrmBairros().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnAdd;
private javax.swing.JButton btnAlterar;
private javax.swing.JButton btnAnterior;
private javax.swing.JButton btnCancelar;
private javax.swing.JButton btnDelete;
private javax.swing.JButton btnNovo;
private javax.swing.JButton btnPrimeiro;
private javax.swing.JButton btnProximo;
private javax.swing.JButton btnSair;
private javax.swing.JButton btnSalvar;
private javax.swing.JButton btnUltimo;
private javax.swing.JComboBox<String> jComboBoxCidade;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTableBairro;
private javax.swing.JTextField txtCod;
private javax.swing.JTextField txtNome;
// End of variables declaration
}
package Conexao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class ConectaBanco {
// importar com opçãp java.sql
public Statement stm; // responsável porpreparar e realizar pesquiss no BD
public ResultSet rs; // resp. por armazenar o resultado de uma pesquisa passada para o Statement
public Connection con; // resp. por
private String DRIVER = "org.postgresql.Driver"; // Responsável por identificar o srviço de BD
private String URL = "jdbc:postgresql://localhost:5432/sist_estoq_venda"; // resp. por setar o local do BD
private String USER = "postgres";
private String PASS = "123"; // resp. por realizar a conexaão com o BD
// Paraconectar com outro servidor devee-se mudar os valores declados como privados acima
public void conexao(){ // Método responsável por realizaar a conxão com o BD
try { // tentativa inicial
System.setProperty("jdbc.Drivers", DRIVER); // seta a propriedade do driver de conexão
con = DriverManager.getConnection(URL, USER, PASS);
//JOptionPane.showMessageDialog(null, "Conectado com sucesso!");// realiza a conexã o com o BD
} catch (SQLException ex) { // exceção, caso o try falhe cai aqui
JOptionPane.showMessageDialog(null, "Erro de conexão\n Erro: " +ex.getMessage());
}
}
public void executaSQL(String sql){
try {
stm = con.createStatement(rs.TYPE_SCROLL_INSENSITIVE, rs.CONCUR_READ_ONLY);
rs = stm.executeQuery(sql);
} catch (SQLException ex) {
//JOptionPane.showMessageDialog(null, "Erro NO EXECUTAsql() \n Erro: " +ex.getMessage());
}
}
public void desconecta(){ // Método para fechara a conexão com o BD
try {
con.close();
//JOptionPane.showMessageDialog(null, "Conexão fechada com sucesso!", "Aviso", JOptionPane.INFORMATION_MESSAGE);
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Erro ao fechara conexão \n Erro: " +ex.getMessage());
}
}
}
Passkeys: A Evolução da Autenticação Digital
Instalação de distro Linux em computadores, netbooks, etc, em rede com o Clonezilla
Título: Descobrindo o IP externo da VPN no Linux
Armazenando a senha de sua carteira Bitcoin de forma segura no Linux
Enviar mensagem ao usuário trabalhando com as opções do php.ini
Instalando Brave Browser no Linux Mint 22
vídeo pra quem quer saber como funciona Proteção de Memória:
Encontre seus arquivos facilmente com o Drill
Mouse Logitech MX Ergo Advanced Wireless Trackball no Linux
Compartilhamento de Rede com samba em modo Público/Anônimo de forma simples, rápido e fácil
Remoção de propaganda com o programa Comskip[AJUDA] (4)
Instalação do drive do adaptador wiffi (5)
Linux Lite Demorando Muito Para Ligar (1)