Bom dia gurizada, peço que me desculpem caso já tenha um topico como este mas realmente não achei, assim, tenho um jframe com o cadastro de clientes, e um jdialog com a pesquisa de cep, funcionando, oque eu queria é o seguinte, pegar a linha selecionada na tabela do frame ceps, e inserir no frame clientes, já tente de varias maneiras e não consegui.
desde já obrigado.
Pegar valor da tabela de um jdialog e inserir em um outo jframe
19 Respostas
na tela que chama o buscador de cep deve ter um metodo assim:
public void setCep(String cep){};
dae no construtor da classe que busca cep vc vai passar a sua classe que tem esse metodo.
quando a pessoa clicar no cep escolhido vc chama o metodo setCep e fecha a tela.
entendeu?
Cara desculpa, é que sou iniciante, se não fosse pedir de mais e você pudesse me dar um pequeno exemplo, a classe em que eu cadastro o cliente é a Clientes, e a que eu pesquiso o cep para inserir é a CepInsert, vlw.
sem problemas. faz assim:
class Clientes {
public void setCep(String cep){
// aqui vc coloca o codigo pra preencher o campo de cep
}}
class CepInsert {
private Clientes clie;
public CepInsert(Clientes clie){
this.clie = clie;
}
// quando clicar no evento da tabela e escolher o cep, vc chama o metodo assim:
clie.setCep(AQUI VC PASSA O VALOR DO CEP);
}
abrax
outro Exemplo.
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class guj extends JFrame{
private JButton butao;
private JPanel painel;
private JTextField txt;
public guj(){
painel=new JPanel();
painel.setLayout(new FlowLayout());
JLabel lb=new JLabel("digite o cep:");
butao=new JButton("NOVA JANELA");
butao.addActionListener(new Sair());
painel.add(lb);
txt=new JTextField(15);
painel.add(txt);
painel.add(butao);
this.add(painel);
this.setSize(300,200);
this.setResizable(false);
this.setVisible(true);
}
private class Sair implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
new guj2(txt.getText());
}
}
public static void main(String[]args){
new guj();
}
}
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class guj2 extends JFrame{
private JButton butao;
private JPanel painel;
private JLabel lb;
public guj2(String cep){
painel=new JPanel();
painel.setLayout(new FlowLayout());
lb=new JLabel(cep);
painel.add(lb);
this.add(painel);
this.setSize(300,200);
this.setResizable(false);
this.setVisible(true);
}
}
isso mesmo, você pode efetuar essa comunicação atravéz dos construtores. att
tchê não que eu seja burro, mas não consegui utilizar os exemplos, tive que dar um modificada para mais ou menos funcionar, ficou assim:
Classe Clientes:public void setCliente( CorreiosBean cliente) {
tfBairro.setText(cliente.getBairro());
tfPesquisaCep.setText(cliente.getCep());
tfCidade.setText(cliente.getCidade());
tfRua.setText(cliente.getLogradouro());
tfUf.setText(cliente.getUf());
}
public void Insere(){
if(tbCorreios.getSelectedRow() != -1){
clientes = new Clientes();
clientes.setVisible(true);
clientes.setCliente(correios.get(tbCorreios.getSelectedRow()));
this.dispose();
}
}
clientes = new Clientes();
clientes.setVisible(true);
ele gera erros:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at br.com.financeira.view.CepIncert.Insere(CepIncert.java:41)
at br.com.financeira.view.CepIncert.btInsereActionPerformed(CepIncert.java:178)
at br.com.financeira.view.CepIncert.access$200(CepIncert.java:28)
at br.com.financeira.view.CepIncert$3.actionPerformed(CepIncert.java:106)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6504)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6269)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4860)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4686)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2713)
at java.awt.Component.dispatchEvent(Component.java:4686)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:707)
at java.awt.EventQueue.access$000(EventQueue.java:101)
at java.awt.EventQueue$3.run(EventQueue.java:666)
at java.awt.EventQueue$3.run(EventQueue.java:664)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:680)
at java.awt.EventQueue$4.run(EventQueue.java:678)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:677)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
CONSTRUÍDO COM SUCESSO (tempo total: 14 segundos)
Muito obrigado pela atenção de vocês!
desculpe, esqueci de falar. mudei de Jdialog para Jframe.
faça assim na sua view onde estao os JTextField:
Clientes cliente =new Clientes();
cliente.setBairro(tfBairro.getText());
cliente.setCep(tfPesquisaCep.getText());
...
new CepInsert(cliente);
CepInsert(Cientes cliente){}
if(cep == null){
Clientes cliente = new Clientes();
cep = new CepIncert(cliente);
cep.setVisible(true);
}
public CepIncert(Clientes cliente) {
initComponents();
}
public void Insere(){
if(tbCorreios.getSelectedRow() != -1){
clientes.setCliente(correios.get(tbCorreios.getSelectedRow()));
this.dispose();
}
}
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(CepIncert.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CepIncert.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CepIncert.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CepIncert.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CepIncert().setVisible(true);
}
});
}
cara vc nao entendeu.
fiz exemplo.
veja:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Cliente extends JFrame {
private String nome;
private String sexo;
private String cpf;
private JTextField txtnome,txtsexo,txtcpf;
private JLabel lbNome,lbSexo,lbCpf;
private JPanel painel;
private JButton butao;
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
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;
}
public Cliente(){
painel=new JPanel();
painel.setLayout(new FlowLayout());
lbNome=new JLabel("Nome");
txtnome=new JTextField(15);
lbSexo=new JLabel("Sexo");
txtsexo=new JTextField(15);
lbCpf=new JLabel("cpf");
txtcpf=new JTextField(15);
butao=new JButton("passar valores");
butao.addActionListener(new util());
painel.add(lbNome);
painel.add(txtnome);
painel.add(lbSexo);
painel.add(txtsexo);
painel.add(lbCpf);
painel.add(txtcpf);
painel.add(butao);
this.add(painel);
this.setSize(240,200);
this.setVisible(true);
}
private class util implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
Cliente cliente=new Cliente();
cliente.setNome(txtnome.getText());
cliente.setCpf(txtcpf.getText());
cliente.setSexo(txtsexo.getText());
new JANELA(cliente);
}
}
public static void main(String[] args) {
new Cliente();
}
}
dentro do evento ele cria um cliente e atribui os valores digitados ao cliente.metodo set…
ele chama uma nova classe(JANELA) passando como parametro os dados do cliente.
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class JANELA extends JFrame {
private JTextField txtnome,txtsexo,txtcpf;
private JLabel lbNome,lbSexo,lbCpf;
private JPanel painel;
private JButton butao;
public JANELA(Cliente cliente){
painel=new JPanel();
painel.setLayout(new FlowLayout());
lbNome=new JLabel("Nome");
txtnome=new JTextField(cliente.getNome(),15);
lbSexo=new JLabel("Sexo");
txtsexo=new JTextField(cliente.getSexo(),15);
lbCpf=new JLabel("cpf");
txtcpf=new JTextField(cliente.getCpf(),15);
painel.add(lbNome);
painel.add(txtnome);
painel.add(lbSexo);
painel.add(txtsexo);
painel.add(lbCpf);
painel.add(txtcpf);
this.add(painel);
this.setSize(240,200);
this.setVisible(true);
}
}
essa classe recebe os dados do cliente e os mostra nos JTextfield…metodo get
Cara na verdade assim eu consegui fazer, neste exemplo que você me passou ele abre um novo form e passa os valores, porém no meu caso o form já esta aberto, eu abro um segundo form para pesquisar os valores e inserir no que já esta aberto, entende?
vou postar o codigo completo:
classe Clientes:package br.com.financeira.view;
import br.com.financeira.cliente.ClienteBean;
import br.com.financeira.cliente.ClienteControl;
import br.com.financeira.correios.CorreiosBean;
import br.com.financeira.correios.CorreiosBean;
import br.com.financeira.correios.CorreiosControl;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
public class Clientes extends javax.swing.JFrame {
//DefaultTableModel tmClientes = new DefaultTableModel(null, new String[]{"Código", "Nome", "Cpf", "Data Nascimento", "Telefone"});
DefaultTableModel tmClientes = new DefaultTableModel(new Object[] {
"Código", "Nome", "Cpf", "Data Nascimento", "Telefone" }, 0) {
public boolean isCellEditable(int rowIndex, int mColIndex){
return false;
}
};
ListSelectionModel lsmClientes;
List<ClienteBean> clientes;
String tipoCadastro;
CepIncert cep;
Principal principal;
// Clientes cliente;
// Correios correios;
/** Creates new form Clientes */
public Clientes() {
initComponents();
}
public void capturarDataSys(){
GregorianCalendar data = new GregorianCalendar(TimeZone.getTimeZone("GMT-3"),new Locale("pt_BR"));
Date d = data.getTime();
String dt[] = {String.valueOf(d.getDate()), String.valueOf((d.getMonth() + 1)), String.valueOf((d.getYear() + 1900))};
if (Integer.parseInt(dt[0]) < 10) {
dt[0] = "0" + dt[0];
}
if (Integer.parseInt(dt[1]) < 10) {
dt[1] = "0" + dt[1];
}
tfDatacadastro.setText(dt[0] + dt[1] + dt[2]);
}
protected void tbClientesLinhaSelecionada(JTable tb){
if (tb.getSelectedRow() != -1){
tfCodigo.setText(clientes.get(tb.getSelectedRow()).getCodigo().toString());
tfNome.setText(clientes.get(tb.getSelectedRow()).getNome());
tfCpf.setText(clientes.get(tb.getSelectedRow()).getCpf());
tfRg.setText(clientes.get(tb.getSelectedRow()).getRg());
tfOrgao_rg.setText(clientes.get(tb.getSelectedRow()).getOrgao_rg());
tfNascimento.setText(clientes.get(tb.getSelectedRow()).getNascimento());
tfDatacadastro.setText(clientes.get(tb.getSelectedRow()).getData_cadastro());
tfProfissao.setText(clientes.get(tb.getSelectedRow()).getProfissao());
tfTelefone.setText(clientes.get(tb.getSelectedRow()).getFone());
tfSalario.setText(clientes.get(tb.getSelectedRow()).getRenda());
tfCel.setText(clientes.get(tb.getSelectedRow()).getCel());
tfRecados.setText(clientes.get(tb.getSelectedRow()).getFone_referencia());
tfEmail.setText(clientes.get(tb.getSelectedRow()).getEmail());
tfPesquisaCep.setText(clientes.get(tb.getSelectedRow()).getCep());
tfRua.setText(clientes.get(tb.getSelectedRow()).getRua());
tfNum.setText(clientes.get(tb.getSelectedRow()).getNum_resid());
tfCidade.setText(clientes.get(tb.getSelectedRow()).getCidade());
tfBairro.setText(clientes.get(tb.getSelectedRow()).getBairro());
// tfUf.setText(clientes.get(tb.getSelectedRow()).getUf());
cbUf.setSelectedItem(clientes.get(tb.getSelectedRow()).getUf());
tfComplemento.setText(clientes.get(tb.getSelectedRow()).getComplemento());
tfNumBeneficio.setText(clientes.get(tb.getSelectedRow()).getNum_beneficio());
tfDataemprestimo.setText(clientes.get(tb.getSelectedRow()).getData_emprestimo());
tfObs.setText(clientes.get(tb.getSelectedRow()).getObs());
// tfTipoBeneficio.setText(clientes.get(tb.getSelectedRow()).getTipo_beneficio());
cbTipoBeneficio.setSelectedItem(clientes.get(tb.getSelectedRow()).getTipo_beneficio());
} else {
tfNome.setText("");
tfCpf.setText("");
tfRg.setText("");
tfOrgao_rg.setText("");
tfNascimento.setText("");
tfDatacadastro.setText("");
tfProfissao.setText("");
tfTelefone.setText("");
tfSalario.setText("");
tfCel.setText("");
tfRecados.setText("");
tfEmail.setText("");
tfPesquisaCep.setText("");
tfRua.setText("");
tfNum.setText("");
tfCidade.setText("");
tfBairro.setText("");
tfUf.setText("");
cbUf.setSelectedItem("");
tfComplemento.setText("");
tfNumBeneficio.setText("");
tfDataemprestimo.setText("");
tfObs.setText("");
tfTipoBeneficio.setText("");
cbTipoBeneficio.setSelectedItem("");
}
}
protected void cadastraCliente(){
if (verificarCampos() && verificarUF()){
ClienteBean cliente = new ClienteBean();
cliente.setNome(tfNome.getText().trim());
cliente.setCpf(tfCpf.getText().trim());
cliente.setRg(tfRg.getText().trim());
cliente.setOrgao_rg(tfOrgao_rg.getText().trim());
cliente.setNascimento(tfNascimento.getText().trim());
cliente.setData_cadastro(tfDatacadastro.getText().trim());
cliente.setProfissao(tfProfissao.getText().trim());
cliente.setFone(tfTelefone.getText().trim());
cliente.setRenda(tfSalario.getText().trim());
cliente.setCel(tfCel.getText().trim());
cliente.setFone_referencia(tfRecados.getText().trim());
cliente.setEmail(tfEmail.getText().trim());
cliente.setCep(tfPesquisaCep.getText().trim());
cliente.setRua(tfRua.getText().trim());
cliente.setNum_resid(tfNum.getText().trim());
cliente.setCidade(tfCidade.getText().trim());
cliente.setBairro(tfBairro.getText().trim());
//cliente.setUf(tfUf.getText().trim());
cliente.setUf(cbUf.getSelectedItem().toString());
cliente.setComplemento(tfComplemento.getText().trim());
cliente.setNum_beneficio(tfNumBeneficio.getText().trim());
cliente.setData_emprestimo(tfDataemprestimo.getText().trim());
cliente.setObs(tfObs.getText().trim());
cliente.setTipo_beneficio(cbTipoBeneficio.getSelectedItem().toString());
ClienteControl c = new ClienteControl();
c.cadastrarCliente(cliente);
//desabilitarCampos();
}
}
protected void alterarCliente(){
if (verificarCampos() && verificarUF()){
ClienteBean cliente = new ClienteBean();
cliente.setCodigo(clientes.get(tbClientes.getSelectedRow()).getCodigo());
cliente.setNome(tfNome.getText().trim());
cliente.setCpf(tfCpf.getText().trim());
cliente.setRg(tfRg.getText().trim());
cliente.setOrgao_rg(tfOrgao_rg.getText().trim());
cliente.setNascimento(tfNascimento.getText().trim());
cliente.setData_cadastro(tfDatacadastro.getText().trim());
cliente.setProfissao(tfProfissao.getText().trim());
cliente.setFone(tfTelefone.getText().trim());
cliente.setRenda(tfSalario.getText().trim());
cliente.setCel(tfCel.getText().trim());
cliente.setFone_referencia(tfRecados.getText().trim());
cliente.setEmail(tfEmail.getText().trim());
cliente.setCep(tfPesquisaCep.getText().trim());
cliente.setRua(tfRua.getText().trim());
cliente.setNum_resid(tfNum.getText().trim());
cliente.setCidade(tfCidade.getText().trim());
cliente.setBairro(tfBairro.getText().trim());
cliente.setUf(cbUf.getSelectedItem().toString());;
cliente.setComplemento(tfComplemento.getText().trim());
cliente.setNum_beneficio(tfNumBeneficio.getText().trim());
cliente.setData_emprestimo(tfDataemprestimo.getText().trim());
cliente.setObs(tfObs.getText().trim());
cliente.setTipo_beneficio(cbTipoBeneficio.getSelectedItem().toString());
ClienteControl c = new ClienteControl();
c.alterarCliente(cliente);
//desabilitarCampos();
}
}
private void novoCliente(){
// habilitarCampos();
tfNome.setText("");
tfCpf.setText("");
tfRg.setText("");
tfOrgao_rg.setText("");
tfNascimento.setText("");
tfDatacadastro.setText("");
tfProfissao.setText("");
tfTelefone.setText("");
tfSalario.setText("");
tfCel.setText("");
tfRecados.setText("");
tfEmail.setText("");
tfPesquisaCep.setText("");
tfRua.setText("");
tfNum.setText("");
tfCidade.setText("");
tfBairro.setText("");
tfUf.setText("");
tfComplemento.setText("");
tfNumBeneficio.setText("");
tfDataemprestimo.setText("");
tfObs.setText("");
tfTipoBeneficio.setText("");
btSalvar.setEnabled(true);
}
protected boolean verificarUF(){
if (tfUf.getText().length() > 2)
return false;
return true;
}
protected boolean verificarCampos(){
if (!tfNome.getText().trim().equals("")){
return true;
}
return false;
}
protected void listarClientes(){
ClienteControl cli = new ClienteControl();
clientes = cli.listarClientes("%" + tfPesquisaCliente.getText().trim() + "%");
mostrarClientes(clientes);
}
protected void mostrarClientes(List<ClienteBean> clientes){
while (tmClientes.getRowCount() > 0){
tmClientes.removeRow(0);
}
if (clientes.size() == 0){
JOptionPane.showMessageDialog(this, "Nenhum cliente encontrado!");
}else{
String [] campos = new String[] {null, null, null, null, null};
for (int i = 0; i < clientes.size(); i++){
tmClientes.addRow(campos);
tmClientes.setValueAt(clientes.get(i).getCodigo(), i, 0);
tmClientes.setValueAt(clientes.get(i).getNome(), i, 1);
tmClientes.setValueAt(clientes.get(i).getCpf(), i, 2);
tmClientes.setValueAt(clientes.get(i).getNascimento(), i, 3);
tmClientes.setValueAt(clientes.get(i).getFone(), i, 4);
}
}
}
protected void listarCpf(){
ClienteControl cli = new ClienteControl();
clientes = cli.listarCpf("%" + tfPesquisaCpf.getText().trim() + "%");
mostrarCpf(clientes);
}
protected void mostrarCpf(List<ClienteBean> clientes){
while (tmClientes.getRowCount() > 0){
tmClientes.removeRow(0);
}
if (clientes.size() == 0){
int resposta = JOptionPane.showConfirmDialog(this, "Nenhum Cliente encontrado! Deseja Cadastrar?", "Aviso!",
JOptionPane.YES_NO_OPTION);
if (resposta == JOptionPane.YES_OPTION){
jTabbedPane1.setSelectedIndex(1);
//habilitarCampos();
tfNome.requestFocus();
tipoCadastro = "novo";
capturarDataSys();
tfTipoBeneficio.setVisible(false);
cbTipoBeneficio.setVisible(true);
cbUf.setVisible(true);
tfUf.setVisible(false);
novoCliente();
}else{
JOptionPane.showMessageDialog(this, "Nenhum Cliente foi cadastrado!");
jTabbedPane1.setSelectedIndex(0);
listarClientes();
}
}else{
String [] campos = new String[] {null, null, null, null, null};
for (int i = 0; i < clientes.size(); i++){
tmClientes.addRow(campos);
tmClientes.setValueAt(clientes.get(i).getCodigo(), i, 0);
tmClientes.setValueAt(clientes.get(i).getNome(), i, 1);
tmClientes.setValueAt(clientes.get(i).getCpf(), i, 2);
tmClientes.setValueAt(clientes.get(i).getNascimento(), i, 3);
tmClientes.setValueAt(clientes.get(i).getFone(), i, 4);
}
}
}
private void btEmprestimosActionPerformed(java.awt.event.ActionEvent evt) {
}
private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) {
if (tipoCadastro.equals("novo")){
cadastraCliente();
} else if(tipoCadastro.equals("alteracao")){
alterarCliente();
}
JOptionPane.showMessageDialog(this, "Cliente cadastrado com cadastrado!");
jTabbedPane1.setSelectedIndex(0);
jTabbedPane1.setEnabledAt(1, false);
novoCliente();
listarClientes();
}
private void btNovoActionPerformed(java.awt.event.ActionEvent evt) {
tipoCadastro = "novo";
novoCliente();
if(tfPesquisaCpf != null)
JOptionPane.showMessageDialog(null, "Primeiro é necessário pesquisar um cpf!");
tfPesquisaCpf.requestFocus();
/** } else{
tipoCadastro = "novo";
jTabbedPane1.setSelectedIndex(1);
tfTipoBeneficio.setVisible(false);
cbTipoBeneficio.setVisible(true);
cbUf.setVisible(true);
tfUf.setVisible(false);
novoCliente();
}**/
}
private void btOkActionPerformed(java.awt.event.ActionEvent evt) {
listarClientes();
listarCpf();
capturarDataSys();
tfCpf.setText(tfPesquisaCpf.getText().trim());
}
private void btEditarActionPerformed(java.awt.event.ActionEvent evt) {
if(tbClientes.getSelectedRow() == -1){
JOptionPane.showMessageDialog(null, "Por favor selecione um cliente para editar");
}else{
tipoCadastro = "alteracao";
alterarCliente();
jTabbedPane1.setSelectedIndex(1);
jTabbedPane1.setEnabledAt(1, true);
tfTipoBeneficio.setVisible(false);
cbTipoBeneficio.setVisible(true);
cbUf.setVisible(true);
tfUf.setVisible(false);
btSalvar.setEnabled(true);
}
}
private void btInicioActionPerformed(java.awt.event.ActionEvent evt) {
if(principal == null){
principal = new Principal();
principal.setVisible(true);
this.dispose();
}else{
principal.setVisible(true);
principal.setState(JFrame.NORMAL);
}
}
private void btPesquisaCepActionPerformed(java.awt.event.ActionEvent evt) {
}
private void brImportarActionPerformed(java.awt.event.ActionEvent evt) {
jTabbedPane1.setSelectedIndex(1);
jTabbedPane1.setEnabledAt(2, false);
}
private void tbClientesMouseClicked(java.awt.event.MouseEvent evt) {
if(evt.getClickCount() > 1){
tipoCadastro = "alteracao";
alterarCliente();
jTabbedPane1.setSelectedIndex(1);
jTabbedPane1.setEnabledAt(1, true);
tfTipoBeneficio.setVisible(false);
cbTipoBeneficio.setVisible(true);
cbUf.setVisible(true);
tfUf.setVisible(false);
btSalvar.setEnabled(true);
}
}
/**
* @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(Clientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Clientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Clientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Clientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Clientes().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton brImportar;
private javax.swing.JButton btEditar;
private javax.swing.JButton btEmprestimos;
private javax.swing.JButton btExcluir;
private javax.swing.JButton btInicio;
private javax.swing.JButton btNovo;
private javax.swing.JButton btOk;
private javax.swing.JButton btPesquisaCep;
private javax.swing.JButton btSair;
private javax.swing.JButton btSalvar;
private javax.swing.JComboBox cbTipoBeneficio;
public javax.swing.JComboBox cbUf;
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 jLabel14;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel16;
private javax.swing.JLabel jLabel17;
private javax.swing.JLabel jLabel18;
private javax.swing.JLabel jLabel19;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel20;
private javax.swing.JLabel jLabel21;
private javax.swing.JLabel jLabel22;
private javax.swing.JLabel jLabel23;
private javax.swing.JLabel jLabel24;
private javax.swing.JLabel jLabel25;
private javax.swing.JLabel jLabel26;
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.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JSeparator jSeparator1;
private javax.swing.JSeparator jSeparator2;
private javax.swing.JSeparator jSeparator3;
private javax.swing.JTabbedPane jTabbedPane1;
private br.com.financeira.converter.RowSorterToStringConverter rowSorterToStringConverter1;
private javax.swing.JTable tbClientes;
private javax.swing.JTable tbCorreios;
public javax.swing.JTextField tfBairro;
private javax.swing.JTextField tfCel;
public javax.swing.JTextField tfCidade;
private javax.swing.JTextField tfCodigo;
public javax.swing.JTextField tfComplemento;
private javax.swing.JTextField tfCpf;
public javax.swing.JTextField tfDatacadastro;
private javax.swing.JTextField tfDataemprestimo;
private javax.swing.JTextField tfEmail;
private javax.swing.JTextField tfNascimento;
private javax.swing.JTextField tfNome;
public javax.swing.JTextField tfNum;
public javax.swing.JTextField tfNumBeneficio;
private javax.swing.JTextArea tfObs;
private javax.swing.JTextField tfOrgao_rg;
public javax.swing.JTextField tfPesquisaCep;
private javax.swing.JTextField tfPesquisaCliente;
private javax.swing.JTextField tfPesquisaCpf;
private javax.swing.JTextField tfProfissao;
private javax.swing.JTextField tfRecados;
public javax.swing.JTextField tfRg;
public javax.swing.JTextField tfRua;
public javax.swing.JTextField tfSalario;
private javax.swing.JTextField tfTelefone;
public javax.swing.JTextField tfTipoBeneficio;
public javax.swing.JTextField tfUf;
private org.jdesktop.beansbinding.BindingGroup bindingGroup;
// End of variables declaration
DefaultTableModel tmCorreios = new DefaultTableModel(null, new String[]{"Cep", "Rua", "Bairro", "Cidade", "Uf"});
ListSelectionModel lsmCorreios;
List<CorreiosBean> correios;
protected void tbCorreiosLinhaSelecionada(JTable tb){
if (tb.getSelectedRow() != -1){
tfPesquisaCep.setText(correios.get(tb.getSelectedRow()).getCep());
tfRua.setText(correios.get(tb.getSelectedRow()).getLogradouro());
tfCidade.setText(correios.get(tb.getSelectedRow()).getCidade());
tfBairro.setText(correios.get(tb.getSelectedRow()).getBairro());
tfUf.setText(correios.get(tb.getSelectedRow()).getUf());
cbUf.setSelectedItem(correios.get(tb.getSelectedRow()).getUf());
tfComplemento.setText(correios.get(tb.getSelectedRow()).getComplemento());
} else {
tfPesquisaCep.setText("");
tfRua.setText("");
tfCidade.setText("");
tfBairro.setText("");
tfUf.setText("");
tfComplemento.setText("");
}
}
protected void listarCep(){
CorreiosControl cli = new CorreiosControl();
correios = cli.listarCep("%" + tfPesquisaCep.getText().trim() + "%");
mostrarCep(correios);
jTabbedPane1.setEnabledAt(1, true);
jTabbedPane1.setEnabledAt(2, true);
jTabbedPane1.setSelectedIndex(2);
}
protected void mostrarCep(List<CorreiosBean> correios){
while (tmCorreios.getRowCount() > 0){
tmCorreios.removeRow(0);
}
if (correios.size() == 0){
JOptionPane.showMessageDialog(this, "Nenhum cep encontrado!");
}else{
String [] campos = new String[] {null, null, null, null, null};
for (int i = 0; i < correios.size(); i++){
tmCorreios.addRow(campos);
tmCorreios.setValueAt(correios.get(i).getCep(), i, 0);
tmCorreios.setValueAt(correios.get(i).getLogradouro(), i, 1);
tmCorreios.setValueAt(correios.get(i).getBairro(), i, 2);
tmCorreios.setValueAt(correios.get(i).getCidade(), i, 3);
tmCorreios.setValueAt(correios.get(i).getUf(), i, 4);
}
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* CepIncert.java
*
* Created on 30/10/2011, 14:05:28
*/
package br.com.financeira.view;
import br.com.financeira.correios.CorreiosBean;
import br.com.financeira.correios.CorreiosControl;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;
/**
*
* @author rafael
*/
public class CepIncert extends javax.swing.JFrame {
DefaultTableModel tmCorreios = new DefaultTableModel(null, new String[]{"Cep", "Rua", "Bairro", "Cidade", "Uf"});
ListSelectionModel lsmCorreios;
List<CorreiosBean> correios;
Clientes clientes;
/** Creates new form CepIncert */
public CepIncert() {
initComponents();
}
/** 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() {
jScrollPane1 = new javax.swing.JScrollPane();
tbCorreios = new javax.swing.JTable();
tfCep = new javax.swing.JTextField();
tfRua = new javax.swing.JTextField();
tfCidade = new javax.swing.JTextField();
tfUf = new javax.swing.JTextField();
tfBairro = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
btPesquisaCep = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
btInsere = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
tbCorreios.setModel(tmCorreios);
tbCorreios.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
lsmCorreios = tbCorreios.getSelectionModel();
lsmCorreios.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
if (! e.getValueIsAdjusting()){
tbCorreiosLinhaSelecionada(tbCorreios);
}
}
});
jScrollPane1.setViewportView(tbCorreios);
jLabel1.setText("Cep");
btPesquisaCep.setText("Pesquisar");
btPesquisaCep.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btPesquisaCepActionPerformed(evt);
}
});
jLabel2.setText("Rua:");
jLabel3.setText("Bairro:");
jLabel4.setText("Cidade:");
jLabel5.setText("Uf:");
btInsere.setText("Inserir");
btInsere.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btInsereActionPerformed(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()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfCep, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btPesquisaCep)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 358, Short.MAX_VALUE)
.addComponent(btInsere))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfRua, javax.swing.GroupLayout.DEFAULT_SIZE, 599, Short.MAX_VALUE))
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 626, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfBairro, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfCidade, javax.swing.GroupLayout.DEFAULT_SIZE, 203, Short.MAX_VALUE)
.addGap(18, 18, 18)
.addComponent(jLabel5)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfUf, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(48, 48, 48)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(tfCep, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btPesquisaCep)
.addComponent(btInsere))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(tfRua, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(tfBairro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)
.addComponent(tfCidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(tfUf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void btPesquisaCepActionPerformed(java.awt.event.ActionEvent evt) {
listarCep();
}
private void btInsereActionPerformed(java.awt.event.ActionEvent evt) {
}
protected void tbCorreiosLinhaSelecionada(JTable tb){
if (tb.getSelectedRow() != -1){
tfCep.setText(correios.get(tb.getSelectedRow()).getCep());
tfRua.setText(correios.get(tb.getSelectedRow()).getLogradouro());
tfCidade.setText(correios.get(tb.getSelectedRow()).getCidade());
tfBairro.setText(correios.get(tb.getSelectedRow()).getBairro());
tfUf.setText(correios.get(tb.getSelectedRow()).getUf());
} else {
tfCep.setText("");
tfRua.setText("");
tfCidade.setText("");
tfBairro.setText("");
tfUf.setText("");
}
}
protected void listarCep(){
CorreiosControl cli = new CorreiosControl();
correios = cli.listarCep("%" + tfCep.getText().trim() + "%");
mostrarCep(correios);
}
protected void mostrarCep(List<CorreiosBean> correios){
while (tmCorreios.getRowCount() > 0){
tmCorreios.removeRow(0);
}
if (correios.size() == 0){
JOptionPane.showMessageDialog(this, "Nenhum cep encontrado!");
}else{
String [] campos = new String[] {null, null, null, null, null};
for (int i = 0; i < correios.size(); i++){
tmCorreios.addRow(campos);
tmCorreios.setValueAt(correios.get(i).getCep(), i, 0);
tmCorreios.setValueAt(correios.get(i).getLogradouro(), i, 1);
tmCorreios.setValueAt(correios.get(i).getBairro(), i, 2);
tmCorreios.setValueAt(correios.get(i).getCidade(), i, 3);
tmCorreios.setValueAt(correios.get(i).getUf(), i, 4);
}
}
}
/**
* @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(CepIncert.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CepIncert.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CepIncert.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CepIncert.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new CepIncert().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btInsere;
private javax.swing.JButton btPesquisaCep;
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.JScrollPane jScrollPane1;
private javax.swing.JTable tbCorreios;
private javax.swing.JTextField tfBairro;
private javax.swing.JTextField tfCep;
private javax.swing.JTextField tfCidade;
private javax.swing.JTextField tfRua;
private javax.swing.JTextField tfUf;
// End of variables declaration
}
Derrepente acho que seria mais facil, porém não sei se seria possivel vincular os jtextfields do form CepIncert, aos jtextfields do form Clientes, oi vincular a linha selecionada na tabela CepIncerts, aos textfields do form Clientes.
Vector titulo = new Vector();
titulo.add("Nome");
titulo.add("Nascimento:");
titulo.add("CPF:");
titulo.add("Sexo:");
titulo.add("RG::");
Vector dados = new Vector();
for (Cliente a : listaCliente) {
Vector colunas = new Vector();
colunas.add(a.getNomeCliente());
colunas.add(a.getDtNascimento());
colunas.add(a.getCpf());
colunas.add(a.getSexo());
colunas.add(a.getRg());
dados.add(colunas);
}
DefaultTableModel model = new DefaultTableModel(dados, titulo);
isso usando o defaultTablemodel que é o padrao do java.
o vector titulo sera a primeira linha.
o for enquantto tiver cliente em sua lista ele vai adicionar na tabela.
Cara na verdade eu só preciso pegar os valores correspondentes ao cep digitado, por exemplo to cadastrando um cliente, na hora de cadastrar o endereço eu clico no botão cep, ai ele abre uma janela com uma tabela e um campo de texto para eu digitar o cep, depois de clicar em um botão com a linha selecionada na tabela que contem , rua, cidade, bairro e uf, eu quero que ele passe os valores desta tabela para o form que já estava aberto, e este se fecha, mais ou menos isso.
com ele passa os valores eu quis dizer passar os valores da linha selecionada na tabela ceps para os campos de texto do formulario onde to cadastrando os clientes.
ninguém?
Cara acho que vou desistir, já procurei por tudo e nada me ajudou, vlew.
ae gurizada só para constar, ainda não consegui fazer isto, é tão dificil apenas passar o conteudo de um jtextfield de uma classe para outra, rsrsrsrsrrs
mesmo assim vlw.