Manipulação de array em aplicativo GUI com POO

2 respostas
F

Pessoal,

Estou com uma dúvida...

Tenho três classes:

RepositorioCliente
ClienteGui
Cliente

Preciso criar um botão no JFrame que faça a exclusão de uma posição do array.
Ou seja, a exclusão consiste em substituir o objeto excluído pelo próximo, caso seja
diferente de null, liberando a última posição ocupado do array, configurando esta posição como
null.
Este botão excluir deverá chamar o método excluir da classe RepositorioCliente, excluindo o objeto da memória.

package TrabalhoPoo;


public class Cliente {
    
    private String cpf;
    private String nome;
    private String endereco;

    public String getCpf() {
        return cpf;
    }

    public void setCpf(String cpf) {
        this.cpf = cpf;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getEndereco() {
        return endereco;
    }

    public void setEndereco(String endereco) {
        this.endereco = endereco;
    }
    
    /**
     *
     * @return
     */
    @Override
    public String toString() {
      return nome + " - " + cpf;
    }

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

import javax.swing.JOptionPane;

/**
 *
 * @author 71201661
 */
public class ClienteGui extends javax.swing.JFrame {

   private RepositorioCliente rep;
    /**
     * Creates new form Cliente
     */
    public ClienteGui() {
        initComponents();
       
       String valorDigitado = JOptionPane.showInputDialog("Digite algum valor");
       //JOptionPane.showMessageDialog(null, valorDigitado); 
       rep = new RepositorioCliente(Integer.parseInt(valorDigitado)); 
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        cpf = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        nome = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        endereco = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        excluir = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("CPF:");

        jLabel2.setText("Nome:");

        jLabel3.setText("End:");

        jButton1.setText("Salvar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        jLabel4.setText("Cadastro Cliente");

        jButton2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jButton2.setText("Consultar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setText("Limpar");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        excluir.setText("Excluir");
        excluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                excluirActionPerformed(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()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(56, 56, 56)
                        .addComponent(jLabel4))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(cpf, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(nome)
                            .addComponent(endereco)))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(excluir)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel4)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(nome, 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.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(endereco, 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(jButton1)
                    .addComponent(jButton3)
                    .addComponent(excluir))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        Cliente c = new Cliente();
        c.setCpf(cpf.getText());
        c.setEndereco(endereco.getText());
        c.setNome(nome.getText());
        
        //JOptionPane.showMessageDialog(null, c);
        
        rep.cadastrar(c);
        
        cpf.setText("");
        endereco.setText("");
        nome.setText("");
        
       
    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
       String cpfDigitado = cpf.getText();
       
       Cliente cliente = rep.consultar(cpfDigitado);
       
       if (cliente != null){
           nome.setText(cliente.getNome());
           endereco.setText(cliente.getEndereco());
           
       } else {
           JOptionPane.showMessageDialog(null, "Cliente não encontrado");
       }
    }                                        

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        cpf.setText("");
        endereco.setText("");
        nome.setText("");
    }                                        

    private void excluirActionPerformed(java.awt.event.ActionEvent evt) {                                        
        Cliente c = new Cliente();
        rep.deletar(c);
        cpf.setText("");
        endereco.setText("");
        nome.setText("");
        
    }                                       

    
    /**
     * @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(ClienteGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ClienteGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ClienteGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ClienteGui.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new ClienteGui().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JTextField cpf;
    private javax.swing.JTextField endereco;
    private javax.swing.JButton excluir;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JTextField nome;
    // End of variables declaration                   
}
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package TrabalhoPoo;

import javax.swing.JOptionPane;

    
/**
 *
 * @author 71201661
 */
public class RepositorioCliente {
    private Cliente clientes[];
    //private Cliente clientes1[];
    private int posicao_vazia = 0;
    
    public RepositorioCliente (int numeroClientes){
        clientes = new Cliente[numeroClientes];
        //clientes1 = new Cliente[numeroClientes];
    }
    
   // private ClienteGui rep = new ClienteGui();
    
    
   public void cadastrar(Cliente c){
        if (posicao_vazia < clientes.length){
        clientes[posicao_vazia] = c;
        posicao_vazia++;
        } else {
            JOptionPane.showMessageDialog(null, "Sem espaço na memória");
        }
       //if (posicao_vazia < clientes1.length) {
         //  clientes1[posicao_vazia] = c;
          // posicao_vazia++;
       //}
    }
    
    public Cliente consultar (String cpf){
        Cliente clienteEncontrado = null;
        
        for (int i = 0; i < clientes.length; i++){
            Cliente c = clientes[i];
            
            //equals testar conteúdo
            if (c != null && c.getCpf().equals(cpf)) {
                clienteEncontrado = clientes[i];
            }
        }
        return clienteEncontrado;
    }
    
    public void deletar(String cpf){
   
      for(int i=0; i<clientes.length; i++){ // andar no vetor
      
          Cliente c = clientes[i];  // cliente cadastrado na posição i
          
          
          if(c != null && c.getCpf().equals(cpf)){ // se cliente for diferente de nulo e o cpf for igual o digitado
           
              clientes[i] = clientes[i+1];
          }//if
          }//for
       
      /*for(int i=0; i<clientes.length -1; i++){
           if(clientes[i] == null){
            clientes[i] = clientes[i+1];
              //JOptionPane.showMessageDialog(null, clientes[i]);
              
               
           }
        
       }*/
        
        
  }

   
   
        
}

2 Respostas

J

Faltou falar qual a dúvida!

F

Não estou conseguindo criar o método para o botão excluir.

Criado 29 de maio de 2013
Ultima resposta 29 de mai. de 2013
Respostas 2
Participantes 2