[Resolvido] dúvida sobre MVC

Seguindo minha jornada na busca de aprendizado cheguei, mais uma vez, a uma barreira. Eu fiz um “POG”, infelizmente tenho que afirmar, por mais que fique irritado. Nesse meu programa dividi o aplicativo em camadas M.V.C o que a maioria aqui já conhece, na hora que chamo a instrução para inserir os dados tudo funciona bem, porém quando chamo para excluir não funciona.

Segue minhas classes problemáticas, se alguém tiver uma dica agradeceria muito.

camada vew. Classe IfCliente.


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import dominio.Cliente;
import excessao.DnZefinhaExcessao;
import java.awt.Dimension;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import javax.swing.JOptionPane;
import ouvinte.OuvinteDeGUICadastroClientes;
import ouvinte.OuvinteDeGuiIFCliente;
import ouvinte.OuvinteDeGuiIFCliente.OuvinteExcluirSocio;
import persistencia.impl.Conexao;

/**
 *
 * @author User
 */
public class IFCliente extends javax.swing.JInternalFrame {

    private List clientes;
    

    Conexao conn = new Conexao();
    PreparedStatement pst;
    ResultSet rs;
    
       
    /**
     * Creates new form IFCliente
     */
    public IFCliente() {
        initComponents();
        conn.conexao();
        updateTable();
        
        OuvinteDeGuiIFCliente ouvinteExcluirSocio = new OuvinteDeGuiIFCliente(this);
        
    }

    //tabela personalizada
        
   public void updateTable(){
        try{
        String sql = "select * from CLIENTE";
        pst = conn.con.prepareStatement(sql);
        rs = pst.executeQuery();
        
        
        ModeloTabelaClientes modelo = new ModeloTabelaClientes(rs);
        tabelaClientes.setModel(modelo);
        
        conn.con.close();
        rs.close();
        
        }catch(Exception ex){
            JOptionPane.showMessageDialog(null,"não consegui acessar a tabela motivo: /n"+ ex);
        }
    }
   
   
    public Cliente getSocio() throws DnZefinhaExcessao{
    Cliente cliente = null;
    
    int linhaSelecionada = tabelaClientes.getSelectedRow();
    
    if(linhaSelecionada<0){
        throw  new DnZefinhaExcessao("Não foi selecionado nenhum sócio");
    }
    cliente = (Cliente) this.clientes.get(linhaSelecionada);
    
    
    return cliente;
}
      
public int pedirConfirmacao(String mensagem, String titulo, int tipo){
    int resposta = JOptionPane.showConfirmDialog(null, mensagem, titulo, tipo);
    return resposta;
}
    
    /**
     * 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() {

        bNovoCliente = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        tFPesquisar = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        bPesquisar = new javax.swing.JToggleButton();
        bAlterarCliente = new javax.swing.JButton();
        bCompras = new javax.swing.JToggleButton();
        bFechar = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        tabelaClientes = new javax.swing.JTable();
        bAtualizarTabela = new javax.swing.JButton();
        bExcluirCliente = new javax.swing.JButton();

        setClosable(true);
        setTitle("Dona Zefinha - Clientes");

        bNovoCliente.setText("NOVO Cliente");
        bNovoCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bNovoClienteActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("PESQUISAR CLIENTE"));

        jLabel1.setText("Nome");

        bPesquisar.setText("Pesquisar Cliente");
        bPesquisar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bPesquisarActionPerformed(evt);
            }
        });

        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()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(tFPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, 267, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(bPesquisar)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(13, 13, 13)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tFPesquisar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(bPesquisar))
                .addContainerGap(34, Short.MAX_VALUE))
        );

        bAlterarCliente.setText("Alterar Cliente");

        bCompras.setText("Compras");

        bFechar.setText("Fechar");
        bFechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bFecharActionPerformed(evt);
            }
        });

        tabelaClientes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane2.setViewportView(tabelaClientes);

        bAtualizarTabela.setText("Atualizar Tabela");
        bAtualizarTabela.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bAtualizarTabelaActionPerformed(evt);
            }
        });

        bExcluirCliente.setText("Ecluir Cliente");
        bExcluirCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bExcluirClienteActionPerformed(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)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 662, Short.MAX_VALUE)
                        .addComponent(bFechar))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(bCompras)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(bAtualizarTabela))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(bNovoCliente)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(bAlterarCliente)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(bExcluirCliente)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 192, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(66, 66, 66)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bCompras)
                    .addComponent(bAtualizarTabela))
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bNovoCliente)
                    .addComponent(bAlterarCliente)
                    .addComponent(bExcluirCliente))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 102, Short.MAX_VALUE)
                .addComponent(bFechar)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>

    private void bFecharActionPerformed(java.awt.event.ActionEvent evt) {                                        
        // TODO add your handling code here:
        this.dispose();
       
    }                                       

    private void bNovoClienteActionPerformed(java.awt.event.ActionEvent evt) {                                             
        // novo cliente
       GUIManipulacaoCliente gUIManipulacaoCliente = new GUIManipulacaoCliente();
       OuvinteDeGUICadastroClientes ouvinteDeGUICadastroClientes = new OuvinteDeGUICadastroClientes(gUIManipulacaoCliente);
       this.getParent().add(gUIManipulacaoCliente);
       gUIManipulacaoCliente.setPosicao();
       gUIManipulacaoCliente.setVisible(true);
    }                                            

    private void bAtualizarTabelaActionPerformed(java.awt.event.ActionEvent evt) {                                                 
        
    }                                                

    private void bExcluirClienteActionPerformed(java.awt.event.ActionEvent evt) {                                                

    }                                               

    private void bPesquisarActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    // Variables declaration - do not modify
    private javax.swing.JButton bAlterarCliente;
    private javax.swing.JButton bAtualizarTabela;
    private javax.swing.JToggleButton bCompras;
    private javax.swing.JButton bExcluirCliente;
    private javax.swing.JButton bFechar;
    private javax.swing.JButton bNovoCliente;
    private javax.swing.JToggleButton bPesquisar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField tFPesquisar;
    private javax.swing.JTable tabelaClientes;
    // End of variables declaration

//metodo setPosicao
    public void setPosicao() {
        Dimension d = this.getDesktopPane().getSize();
        this.setLocation((d.width - this.getSize().width) / 6, (d.height -
        this.getSize().height) / 6);
}

    public void bExcluirClienteAddActionListener(OuvinteExcluirSocio ouvinte) {
        bExcluirCliente.addActionListener(ouvinte);
    }

   
   
}

camada vew. Classe do modelo da tabela


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

/**
 *
 * @author User
 */
 
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
 
/**
 *
 * @author Eduardo Folly
 */
public class ModeloTabelaClientes extends AbstractTableModel {
 
    private List lista = new ArrayList();
    private String[] colunas;
 
    public ModeloTabelaClientes(ResultSet rs) throws SQLException {
        ResultSetMetaData rsmd = rs.getMetaData();
 
        int cols = rsmd.getColumnCount();
 
        int[] tipos = new int[cols];
        colunas = new String[cols];
 
        for (int c = 1; c <= cols; c++) {
            tipos[c - 1] = rsmd.getColumnType(c);
            colunas[c - 1] = rsmd.getColumnName(c);
        }
 
        while (rs.next()) {
            Object[] objs = new Object[cols];
 
            for (int c = 1; c <= cols; c++) {
                int tipo = tipos[c - 1];
 
                if (tipo == java.sql.Types.VARCHAR) {
                    objs[c - 1] = rs.getString(c);
                } else if (tipo == java.sql.Types.FLOAT) {
                    objs[c - 1] = rs.getFloat(c);
                } else {
                    objs[c - 1] = rs.getObject(c);
                }
            }
 
            lista.add(objs);
        }
    }
 
    @Override
    public int getRowCount() {
        return lista.size();
    }
 
    @Override
    public int getColumnCount() {
        return colunas.length;
    }
 
    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Object[] row = (Object[]) lista.get(rowIndex);
        
        return row[columnIndex];
    }
 
    @Override
    public String getColumnName(int column) {
        return colunas[column];
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return false;
    }
    public void excluir(){
        lista.remove(this);
        fireTableDataChanged();
    }
    
}

camada vew. Classe ouvinte

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ouvinte;

import GUI.GUIMensagem;
import GUI.IFCliente;
import controle.ControleCliente;
import dominio.Cliente;
import excessao.DnZefinhaExcessao;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;

/**
 *
 * @author User
 */
public class OuvinteDeGuiIFCliente {
    
    private IFCliente iFCliente;

    public OuvinteDeGuiIFCliente(IFCliente iFCliente) {
        
        this.iFCliente = iFCliente;
        iFCliente.bExcluirClienteAddActionListener(new OuvinteExcluirSocio());
    }
    
    public class OuvinteExcluirSocio implements ActionListener{

       
        public void actionPerformed(ActionEvent e) {
            
            
            
            try {
                Cliente cliente = new Cliente();
                StringBuffer mensagem = new StringBuffer("Confirmar a exclusão do Cliente: ");
                
                mensagem.append("\nCódigo: " + cliente.getId_cliente());
                mensagem.append("\nNome: " + cliente.getNome());
                int resposta = iFCliente.pedirConfirmacao(mensagem.toString(), "Fichas Dn Zefinha - Exclusão de registro", JOptionPane.YES_NO_OPTION);
                
                if (resposta == JOptionPane.OK_OPTION) {
                ControleCliente controle = new ControleCliente();
                controle.excluirCliente(cliente);
                GUIMensagem.exibirMensagem("Sócio excluído com sucesso!", "Cadastro de  Sócio", false);
                }
                
                
            } catch (DnZefinhaExcessao ex) {
                GUIMensagem.exibirMensagem(ex.getMessage(), "Fichas DnZefinha - Clientes", true);
            }
        }
    
    
    }
}

camada controller. Classe de controle

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controle;

import dominio.Cliente;
import excessao.DnZefinhaExcessao;
import persistencia.impl.FabricaPersistencia;
import persistencia.impl.intefaces.IFabricaPersistencia;
import persistencia.impl.intefaces.IGatewayCliente;

/**
 *
 * @author User
 */
public class ControleCliente {
    
     
    
    public void gravarSocio(Cliente cliente) throws DnZefinhaExcessao {
        IFabricaPersistencia fabricaPersistencia = new FabricaPersistencia();
        IGatewayCliente gatewayCliente = fabricaPersistencia.getGatewayCliente();
        gatewayCliente.gravarcliente(cliente);
        
        
}
        public void excluirCliente(Cliente cliente) throws DnZefinhaExcessao{
            IFabricaPersistencia fabricaPersistencia = new FabricaPersistencia();
            IGatewayCliente gatwayCliente = fabricaPersistencia.getGatewayCliente();
            gatwayCliente.excluirCliente(cliente);
        }
        
    
}

camada model.dominio Classe Cliente


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dominio;

import excessao.DnZefinhaExcessao;
import java.util.Collections;
import java.util.List;

/**
 *
 * @author User
 */
public class Cliente {
    private List compras;
    
    private Long id_cliente;
    private String nome;
    private String cpf;
    private String endereco;
    private String telefone;

    /**
     * @return the Compras
     */
    public List getCompras() {
        return compras;
    }

    /**
     * @param Compras the Compras to set
     */
    public void setCompras(List Compras) {
        this.compras = Compras;
    }

    public Long getId_cliente() {
        return id_cliente;
    }
    /**
     * @return the nome
     */
    public String getNome() {
        return nome;
    }

    /**
     * @param nome the nome to set
     */
   public void setNome(String nome) throws DnZefinhaExcessao{
        if(!this.isNomeValido(nome.trim())){
            throw new DnZefinhaExcessao("O nome do Cliente deve ser informado!");
        }
        this.nome = nome;
    }

    /**
     * @return the cpf
     */
    public String getCpf() {
        return cpf;
    }

    /**
     * @param cpf the cpf to set
     */
    public void setCpf(String cpf) {
        this.cpf = cpf;
    }

    /**
     * @return the endereco
     */
    public String getEndereco() {
        return endereco;
    }

    /**
     * @param endereco the endereco to set
     */
    public void setEndereco(String endereco) {
        this.endereco = endereco;
    }

    /**
     * @return the telefone
     */
    public String getTelefone() {
        return telefone;
    }

    /**
     * @param telefone the telefone to set
     */
    public void setTelefone(String telefone) {
        this.telefone = telefone;
    }
    
    //metodos pessoais;
    private boolean isNomeValido (String nome){
        if(nome == null || nome.length()==0){
            return false;
        }else{
            return true;
        }
    }

    
    //metodos para COMPRAS
public void adicionarCompra(Compras compra){
        this.compras.add(compra);
}
public void removerCompra(Compras compra){
    this.compras.remove(compra);
}
    public void removerCompra(int indice){
        this.compras.remove(indice);
    }
    public List getDependentes(){
        return Collections.unmodifiableList(compras);
    }

    /**
     * @return the id_cliente
     */
    
}

camada model. gatewayCliente

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package persistencia.impl;

import dominio.Cliente;
import dominio.Compras;
import excessao.DnZefinhaExcessao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Iterator;
import persistencia.impl.intefaces.IGatewayCliente;

/**
 *
 * @author User
 */
public class GatewayCliente implements IGatewayCliente {
    
    private static final String SQL_MOSTRARcliente = "SELECT * FROM cliente";
    
    private static final String SQL_INCLUIRcliente = "INSERT INTO cliente " + 
            "(nome, cpf, endereco,telefone) " +
            "VALUES ( ?, ?, ?, ?)";
    
    //mais variaveis declaradas
    private static final String SQL_ALTERARcliente =
        "UPDATE cliente SET "+ "nome=?, cpf=?, endereco = ?, telefone = ? "
        + "WHERE id_cliente = ?";
    
private static final String SQL_EXCLUIRcliente =
                "DELETE FROM cliente "
                + "WHERE id_cliente = ?";

//variáveis COMPRAS
private static final String SQL_INCLUIRCOMPRA = "INSERT INTO compra "
    + "(descricao, quant, valor, date, rel_cliente) "
    + "VALUES (?, ?, ?, ?, ?)";
private static final String SQL_EXCLUIRCOMPRA = "DELETE FROM compra "
    + "WHERE rel_cliente = ?";


public void mostrarCliente(Cliente cliente) throws DnZefinhaExcessao{
   
    
}
    
private void incluirCliente(Cliente cliente) throws DnZefinhaExcessao {
    if (cliente == null) {
        String mensagem = "Não foi informado o cliente a cadastrar.";
        throw new DnZefinhaExcessao(mensagem);
    }
    Connection con = null;
    PreparedStatement stmt = null;
    try {
        con = GerenciadorDeConexao.getConexao();
        stmt = con.prepareStatement(SQL_INCLUIRcliente);
        //GeradorDeChave geradorDeChave = new GeradorDeChave("cliente");
        //long codigocliente = geradorDeChave.getProximoCodigo();
        
        stmt.setString(1, cliente.getNome());
        stmt.setString(2, cliente.getCpf());
        stmt.setString(3, cliente.getEndereco());
        stmt.setString(4, cliente.getTelefone());
        
        stmt.executeUpdate();
        
    } catch (SQLException exc) {
        StringBuffer mensagem = new StringBuffer("Não foi possível incluir o cliente.");
        mensagem.append("\nMotivo: " + exc.getMessage());
        throw new DnZefinhaExcessao(mensagem.toString());
    } finally {
        GerenciadorDeConexao.closeConexao(con, stmt);
    }
}
   @Override
    public void excluirCliente(Cliente cliente) throws DnZefinhaExcessao{
        if (cliente == null) {
            String mensagem = "Não foi informado o sócio a excluir.";
            throw new DnZefinhaExcessao(mensagem);
        }
        Connection con = null;
        PreparedStatement stmt = null;
        try {
            con = GerenciadorDeConexao.getConexao();
            stmt = con.prepareStatement(SQL_EXCLUIRcliente);
            stmt.setLong(1, cliente.getId_cliente());
            
            stmt.executeUpdate();
            
        } catch (SQLException exc) {
            StringBuffer mensagem = new StringBuffer("Não foi possível excluir o cliente.");
            mensagem.append("\nMotivo:" + exc.getMessage());
        throw new DnZefinhaExcessao(mensagem.toString());
        
        } finally {
            GerenciadorDeConexao.closeConexao(con, stmt);
        }
    }//fim do metodo

    @Override
    public void gravarcliente(Cliente cliente) throws DnZefinhaExcessao {
        
                        incluirCliente(cliente);
        
    }
    private void alterarcliente(Cliente cliente) throws DnZefinhaExcessao {
                
                Connection con = null;
                PreparedStatement stmt = null;
                try {
                con = GerenciadorDeConexao.getConexao();
                stmt = con.prepareStatement(SQL_ALTERARcliente);
                stmt.setString(1, cliente.getNome());
                stmt.setString(2, cliente.getCpf());
                stmt.setString(3, cliente.getEndereco());
                stmt.setString(4, cliente.getTelefone());
                stmt.setLong(5, cliente.getId_cliente());
                
                stmt.executeUpdate();
                
                atualizarDependentes(cliente);
                
        }catch (SQLException exc){
            StringBuffer mensagem = new StringBuffer("Não foi possível atualizar os dados do cliente.");
            mensagem.append("\nMotivo:"+exc.getMessage());
            throw new DnZefinhaExcessao(mensagem.toString());
        }finally{
            GerenciadorDeConexao.closeConexao(con,stmt);
        }
    }//fim do metodo
   
    
    
    //metodos para DEPENDENTES
    @Override
    public void atualizarDependentes(Cliente cliente) throws DnZefinhaExcessao{
        this.excluirCompra(cliente);
        this.incluirCompra(cliente);
    }
    
    private void excluirCompra(Cliente cliente) throws DnZefinhaExcessao {
        if (cliente == null) {
            String mensagem = "Não foi informado o cliente a alterar";
            throw new DnZefinhaExcessao(mensagem);
        }
            Connection con = null;
            PreparedStatement stmt = null;
        try {
            con = GerenciadorDeConexao.getConexao();
            stmt = con.prepareStatement(SQL_EXCLUIRCOMPRA);
            stmt.setLong(1, cliente.getId_cliente());
            
            stmt.executeUpdate();
            
        } catch (SQLException exc) {
            StringBuffer msg = new StringBuffer("Não foi possível atualizar as compras do sócio.");
            msg.append("\nMotivo: " + exc.getMessage());
            throw new DnZefinhaExcessao(msg.toString());
        } finally {
            GerenciadorDeConexao.closeConexao(con, stmt);
        }
   }
    
    private void incluirCompra(Cliente cliente) throws DnZefinhaExcessao {
        if (cliente == null) {
            String mensagem = "Não foi informado o cliente a alterar";
            throw new DnZefinhaExcessao(mensagem);
        }
        Connection con = null;
        PreparedStatement stmt = null;
        try {
            con = GerenciadorDeConexao.getConexao();
            stmt = con.prepareStatement(SQL_INCLUIRCOMPRA);
            long codigo = 1;
            Iterator dependentes = cliente.getDependentes().iterator();
            while(dependentes.hasNext()){
                Compras compra = (Compras)dependentes.next();
                stmt.setString(1, compra.getDescricao());
                stmt.setInt(2, compra.getQuant());
                stmt.setDouble(3, compra.getValor());
                java.util.Date dataCompra = compra.getData();
                stmt.setDate(4, new java.sql.Date(dataCompra.getTime()));
                
                stmt.executeUpdate();

                codigo++;
            }
        } catch (SQLException exc) {
            StringBuffer msg = new StringBuffer("Não foi possível atualizar as compras do cliente.");
            msg.append("\nMotivo: " + exc.getMessage());
            throw new DnZefinhaExcessao(msg.toString());
        } finally {
            GerenciadorDeConexao.closeConexao(con, stmt);

        }
    }

    public void mostrarCliente() throws DnZefinhaExcessao {
    Connection con = null;
    PreparedStatement stmt= null;
    try {
        con = GerenciadorDeConexao.getConexao();
        stmt = con.prepareStatement(SQL_MOSTRARcliente);
        
        stmt.executeQuery();
        
        
    } catch (SQLException exc) {
        StringBuffer mensagem = new StringBuffer("Não foi possível mostrar os dados na tabela.");
        mensagem.append("\nMotivo: " + exc.getMessage());
        throw new DnZefinhaExcessao(mensagem.toString());
    }finally{
        GerenciadorDeConexao.closeConexao(con);
    }
    }

   
}

modelo.persistencia interface


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package persistencia.impl.intefaces;

import dominio.Cliente;
import excessao.DnZefinhaExcessao;

/**
 *
 * @author User
 */
public interface IGatewayCliente {
    
    void mostrarCliente(Cliente cliente)throws DnZefinhaExcessao;
    
    void atualizarDependentes(Cliente cliente) throws DnZefinhaExcessao;

    void excluirCliente(Cliente cliente) throws DnZefinhaExcessao;

    void gravarcliente(Cliente cliente) throws DnZefinhaExcessao;
    
    
    
}

Bom os resultados de tudo isso é que quando eu clico no botão para inserir um cliente ele insere normalmente, porém quando eu clico no excluir ele não exclui e retorna um JOptionPane.showMessageDialog com os seguintes dizeres:


| ? Confirmar Exclusão do Cliente: |
| Código: null |
| Nome: null |
| |
| SIM NÃO |

Me perguntas são:

  1. Eu não estou fazendo o programa no Padrão MVC?
  2. Por quê ele não pega o id_cliente?
  3. Terei que refazer o projeto desde o começo???

Todas as respostas serão muito bem vindas. E se não forem respondidas irei entender pois sei que o texto é muito grande. Obrigado.

Sim esqueci de colocar só para efeito de informação:

Se vc clicar no OptionPane.showDialog retorna os seguintes erros:


Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
	at persistencia.impl.GatewayCliente.excluirCliente(GatewayCliente.java:89)
	at controle.ControleCliente.excluirCliente(ControleCliente.java:31)
	at ouvinte.OuvinteDeGuiIFCliente$OuvinteExcluirSocio.actionPerformed(OuvinteDeGuiIFCliente.java:47)
	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)

Amigo, o erro está bem claro, null pointer exception.

try {  
                Cliente cliente = new Cliente();  
                cliente.setId(01);// adicione essas linhas e veja se funciona
                cliente.setNome("Fulano"); // se funcionar, você tem que obter as informações desse cliente de alguma forma. para poder seta-los
                StringBuffer mensagem = new StringBuffer("Confirmar a exclusão do Cliente: ");  
                  
                mensagem.append("\nCódigo: " + cliente.getId_cliente());  
                mensagem.append("\nNome: " + cliente.getNome());  

você tem que setar o id e o nome no cliente. por exemplo.

a sua variavel “cliente” está vazia.

Ou talvez tenha esquecido de instanciar alguma classe… ou não ter setado algum objeto.

Por favor, evite postar uma tonelada de código nos tópicos. Isso não só é pouco efetivo, como espanta usuários.

Além disso, não abuse das letras maiúsculas no título, especialmente para destacar o óbvio (que vc tinha DÚVIDA ou queria AJUDA, por exemplo).

Finalmente, ao postar tópicos, procure ler com atenção a lista de fóruns. Swing e arquitetura MVC não é uma dúvida de Java Básico.

Se refere ou a interface gráfica, ou a arquitetura. Seu tópico foi movido.

Algumas modificações são necessárias no seu código:
a) Implementar corretamente o TableModel para usar classe Cliente, e ter dentro dele um List<Cliente> e não um conjunto de dados aparentemente não relacionados.
Na verdade, o TableModel tem um nome infeliz, pois ele é uma classe de Controle;

b) Retirar o SQL da classe IFCliente, pois isso fere o modelo MVC. Esse SQL deveria ir para a classe GateWayCliente que deveria retornar um List<Cliente>.
Esse list sim, vai para o TableModel, que servirá de controlador para a JTable.

c) Corrigir os JOptionPane.showMessageDialog para que o primeiro parâmetro fosse usado corretamente (com a janela que abriu o JDialog) ao invés de null;

d) Jamais usar List sem tipo. Você deveria ter List<Compra> ao invés de um List puro. O mesmo vale para a lista de dependentes;

e) Retirar o plural do nome da classe Compra. A menos que essa classe represente por si só uma lista;

f) Garantir que todas as conexões, statements e resultsets são fechados, preferencialmente num finally. Note que vc escorregou na classe IFCliente, provavelmente pq o código SQL está no lugar errado, e não no GateWay. A divisão das classes em locais lógicos ajuda a prevenir esse tipo de erro, pois faz com que vc foque melhor nos objetivos do código quando o está implementando (sem falar que auxilia a quem vai escrever os testes);

g) Criar exceções mais específicas. Inclusive, o motivo deveria ser um campo na sua exceção, não somente ser concatenado a sua mensagem. Assim vc deixa a interface gráfica livre para apresenta-lo da forma que quiser. Note que embora a exceção comumente tenha um texto, esse é para o programador, não para ser exibido ao usuário final. Quem deve realmente gerar o texto a ser exibido na tela é a interface gráfica, caso contrário, você está novamente ferindo o MVC, ao transferir uma responsabilidade da view para o model (ou até para uma camada inferior ao model). Em sistemas maiores, é a interface gráfica também que se preocupará com detalhes como internacionalização. Por isso, é sempre bom descrever seus erros com exceções específicas, propriedades com valores, códigos e outros elementos que possam ser facilmente trabalhados na interface

h) Eu removeria totalmente as classes de nome Ouvinte. O Netbeans já está te fornecendo essa abstração. Simplesmente preencha os códigos “actionPerformed” que ele mesmo gera para você.

Cara, Desculpa ai Vini, e obrigado pela aula, mas eu quis colocar o máximo de informação possível, quanto a escolha de onde postar, eu estava em duvida se postava em GUI ou BÁSICO, por achar que sou iniciante e o problema está evolvido no código puro e não na parte gráfica, todavia vejo que tomei a decisão errada, sinto muito pelos erros, mas estou a aprendendo com eles muito obrigado. Postei sem compromisso mesmo, por ver que o código estava muito grande mesmo, obrigado a todos pela a ajuda, vou testar quando chegar em casa.

Obs: eu tentei a forma indicando o id_cliente, exatamente, pela mensagem do erro seria isso, mas não funcionou dessa forma, estou pensando que é um problema do meu projeto. Se não consegui resolvê-lo vou apagar tudo e começar de novo muito obrigado mesmo galera.

[quote=psicoppardo]Cara, Desculpa ai Vini, e obrigado pela aula, mas eu quis colocar o máximo de informação possível, quanto a escolha de onde postar, eu estava em duvida se postava em GUI ou BÁSICO, por achar que sou iniciante e o problema está evolvido no código puro e não na parte gráfica, todavia vejo que tomei a decisão errada, sinto muito pelos erros, mas estou a aprendendo com eles muito obrigado. Postei sem compromisso mesmo, por ver que o código estava muito grande mesmo, obrigado a todos pela a ajuda, vou testar quando chegar em casa.

Obs: eu tentei a forma indicando o id_cliente, exatamente, pela mensagem do erro seria isso, mas não funcionou dessa forma, estou pensando que é um problema do meu projeto. Se não consegui resolvê-lo vou apagar tudo e começar de novo muito obrigado mesmo galera.[/quote]

Sem problemas, só te orientei quanto ao uso do fórum pq sou moderador, e é meu papel fazer isso.

Quanto às críticas ao código, só estava respondendo o que vc mesmo pediu… :wink: