sistemaVendas.AlterarClienteProcurado.java Source code

Java tutorial

Introduction

Here is the source code for sistemaVendas.AlterarClienteProcurado.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package sistemaVendas;

import java.awt.Color;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.InputMismatchException;
import java.util.List;
import javax.swing.JDesktopPane;
import javax.swing.JOptionPane;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

/**
 *
 * @author BRUNO
 */
public class AlterarClienteProcurado extends javax.swing.JInternalFrame {

    /**
     * Creates new form AlterarClienteProcurado
     */
    public AlterarClienteProcurado(JDesktopPane tela) {
        JDesktopPane novaTela = tela;
        initComponents();
        lblCpfValido.setVisible(false);
    }

    public void atualizar(String id, String nome, String sexo, String idade, String telefone, String cpf) {
        txtIdClienteProcurado.setText(id);
        txtNomeClienteProcurado.setText(nome);
        cbxSexoProcurado.setSelectedItem(sexo);
        txtIdadeProcurado.setText(idade);
        txtFoneProcurado.setText(telefone);
        txtCpfProcurado.setText(cpf);
    }

    /**
     * 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">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblIDClienteProcurado = new javax.swing.JLabel();
        lblNomeClienteProcurado = new javax.swing.JLabel();
        lblSexoProcurado = new javax.swing.JLabel();
        lblIdadeProcurado = new javax.swing.JLabel();
        lblTelefoneProcurado = new javax.swing.JLabel();
        lblCpfProcurado = new javax.swing.JLabel();
        cbxSexoProcurado = new javax.swing.JComboBox();
        txtNomeClienteProcurado = new javax.swing.JTextField();
        txtIdClienteProcurado = new javax.swing.JTextField();
        txtIdadeProcurado = new javax.swing.JTextField();
        txtFoneProcurado = new javax.swing.JFormattedTextField();
        txtCpfProcurado = new javax.swing.JFormattedTextField();
        btnAlterarClienteProcurado = new javax.swing.JButton();
        btnCancelarClienteProcurado = new javax.swing.JButton();
        lblCpfValido = new javax.swing.JLabel();
        btnDeletarClienteProcurado = new javax.swing.JButton();

        setClosable(true);
        setTitle("Realizar Alterao do Cliente");

        lblIDClienteProcurado.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblIDClienteProcurado.setText("ID:");

        lblNomeClienteProcurado.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblNomeClienteProcurado.setText("Nome:");

        lblSexoProcurado.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblSexoProcurado.setText("Sexo:");

        lblIdadeProcurado.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblIdadeProcurado.setText("Idade:");

        lblTelefoneProcurado.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblTelefoneProcurado.setText("Telefone:");

        lblCpfProcurado.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblCpfProcurado.setText("CPF:");

        cbxSexoProcurado.setModel(new javax.swing.DefaultComboBoxModel(
                new String[] { "---------------------", "Masculino", "Feminino" }));

        txtNomeClienteProcurado.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N

        txtIdClienteProcurado.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtIdClienteProcurado.setEnabled(false);

        try {
            txtFoneProcurado.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(
                    new javax.swing.text.MaskFormatter("(##)####-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }

        try {
            txtCpfProcurado.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(
                    new javax.swing.text.MaskFormatter("###.###.###-##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        txtCpfProcurado.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtCpfProcuradoFocusLost(evt);
            }
        });

        btnAlterarClienteProcurado.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/ok.png"))); // NOI18N
        btnAlterarClienteProcurado.setText("OK");
        btnAlterarClienteProcurado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAlterarClienteProcuradoActionPerformed(evt);
            }
        });

        btnCancelarClienteProcurado.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/cancel.png"))); // NOI18N
        btnCancelarClienteProcurado.setText("Cancelar");
        btnCancelarClienteProcurado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarClienteProcuradoActionPerformed(evt);
            }
        });

        lblCpfValido.setText("CPF Vlido");

        btnDeletarClienteProcurado.setText("Deletar");
        btnDeletarClienteProcurado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeletarClienteProcuradoActionPerformed(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().addGroup(layout
                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup().addComponent(lblIdadeProcurado)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(txtIdadeProcurado, javax.swing.GroupLayout.PREFERRED_SIZE, 42,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(42, 42, 42).addComponent(lblSexoProcurado)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(cbxSexoProcurado, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(layout.createSequentialGroup().addComponent(lblTelefoneProcurado)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(txtFoneProcurado, javax.swing.GroupLayout.PREFERRED_SIZE, 130,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(0, 0, Short.MAX_VALUE))
                        .addGroup(layout.createSequentialGroup().addGroup(layout
                                .createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addGroup(layout.createSequentialGroup().addGroup(layout
                                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup().addComponent(lblCpfProcurado)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(txtCpfProcurado,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE, 116,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addComponent(btnDeletarClienteProcurado))
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addGroup(layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addGroup(layout.createSequentialGroup()
                                                        .addComponent(btnAlterarClienteProcurado)
                                                        .addPreferredGap(
                                                                javax.swing.LayoutStyle.ComponentPlacement.RELATED,
                                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                                Short.MAX_VALUE)
                                                        .addComponent(btnCancelarClienteProcurado))
                                                .addComponent(lblCpfValido)))
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(layout.createSequentialGroup().addComponent(lblIDClienteProcurado)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(txtIdClienteProcurado,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE, 30,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGroup(layout.createSequentialGroup()
                                                .addComponent(lblNomeClienteProcurado)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(txtNomeClienteProcurado,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE, 330,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))))
                                .addContainerGap(29, Short.MAX_VALUE)))));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addGap(32, 32, 32)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(lblIDClienteProcurado).addComponent(txtIdClienteProcurado,
                                        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(lblNomeClienteProcurado).addComponent(txtNomeClienteProcurado,
                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
                                javax.swing.GroupLayout.Alignment.TRAILING,
                                layout.createSequentialGroup().addGroup(layout
                                        .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(lblIdadeProcurado)
                                        .addComponent(txtIdadeProcurado, javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(lblSexoProcurado).addComponent(cbxSexoProcurado,
                                                javax.swing.GroupLayout.PREFERRED_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGap(25, 25, 25)
                                        .addGroup(layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(lblTelefoneProcurado).addComponent(txtFoneProcurado,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGap(30, 30, 30)
                                        .addGroup(layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(lblCpfProcurado)
                                                .addComponent(txtCpfProcurado,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE,
                                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addComponent(lblCpfValido))
                                        .addGap(81, 81, 81))
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING,
                                        layout.createSequentialGroup().addGroup(layout
                                                .createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                                .addComponent(btnCancelarClienteProcurado)
                                                .addComponent(btnAlterarClienteProcurado)
                                                .addComponent(btnDeletarClienteProcurado)).addContainerGap()))));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    Document doc;
    Element root;

    private void btnAlterarClienteProcuradoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAlterarClienteProcuradoActionPerformed
        if (verificarCPf()) {
            File diretorio = new File("Bancos de Dados");
            File arquivo = new File(diretorio, "BancoCliente.xml");
            String id = txtIdClienteProcurado.getText();
            String nome = txtNomeClienteProcurado.getText();
            String sexo = (String) cbxSexoProcurado.getSelectedItem();
            String idade = txtIdadeProcurado.getText();
            String fone = txtFoneProcurado.getText();
            String cpf = txtCpfProcurado.getText();
            try {
                SAXBuilder builder = new SAXBuilder();
                doc = builder.build(arquivo);
                root = (Element) doc.getRootElement();
                List<Element> clientes = root.getChildren();
                for (int i = 0; i < clientes.size(); i++) {
                    Element cliente = clientes.get(i);
                    if (cliente.getAttributeValue("id").equals(id)) {
                        if (!cliente.getChildText("nome").equals(nome)) {
                            cliente.getChild("nome").setText(nome);
                        }
                        if (!cliente.getChildText("sexo").equals(sexo)) {
                            cliente.getChild("sexo").setText(sexo);
                        }
                        if (!cliente.getChildText("idade").equals(idade)) {
                            cliente.getChild("idade").setText(idade);
                        }
                        if (!cliente.getChildText("telefone").equals(fone)) {
                            cliente.getChild("telefone").setText(fone);
                        }
                        if (!cliente.getChildText("cpf").equals(cpf)) {
                            cliente.getChild("cpf").setText(cpf);
                        }
                    }
                }
                XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
                OutputStream out = new FileOutputStream(new File(diretorio, "BancoCLiente.xml"));
                xout.output(doc, out);
                out.close();
            } catch (JDOMException | IOException e) {
            }
            JOptionPane.showMessageDialog(null, "DADOS ALTERADOS COM SUCESSO!", "Sucesso",
                    JOptionPane.INFORMATION_MESSAGE);
            this.dispose();
        } else {
            JOptionPane.showMessageDialog(null, "CPF INV?LIDO! DIGITE NOVAMENTE!", "ERRO",
                    JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_btnAlterarClienteProcuradoActionPerformed

    private void btnCancelarClienteProcuradoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarClienteProcuradoActionPerformed
        this.dispose();
    }//GEN-LAST:event_btnCancelarClienteProcuradoActionPerformed

    private void txtCpfProcuradoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtCpfProcuradoFocusLost
        if (verificarCPf()) {
            lblCpfValido.setText("CPF V?LIDO!");
            lblCpfValido.setForeground(Color.GREEN);
            lblCpfValido.setVisible(true);
        } else {
            lblCpfValido.setText("CPF INV?LIDO!");
            lblCpfValido.setForeground(Color.RED);
            //          Sound erro = new Sound("./erro.wav");  
            //          SoundManager sm = new SoundManager();  
            //          sm.play(erro); 
            lblCpfValido.setVisible(true);
        }
    }//GEN-LAST:event_txtCpfProcuradoFocusLost

    private void btnDeletarClienteProcuradoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeletarClienteProcuradoActionPerformed
        File diretorio = new File("Bancos de Dados");
        File arquivo = new File(diretorio, "BancoCliente.xml");
        String id = txtIdClienteProcurado.getText();
        try {
            SAXBuilder builder = new SAXBuilder();
            doc = builder.build(arquivo);
            root = (Element) doc.getRootElement();
            List<Element> clientes = root.getChildren();
            for (int i = 0; i < clientes.size(); i++) {
                Element cliente = clientes.get(i);
                if (cliente.getAttributeValue("id").equals(id)) {
                    cliente.getParent().removeContent(cliente);
                }
            }
            XMLOutputter xout = new XMLOutputter(Format.getPrettyFormat());
            OutputStream out = new FileOutputStream(new File(diretorio, "BancoCLiente.xml"));
            xout.output(doc, out);
            out.close();
        } catch (JDOMException | IOException e) {
        }
        JOptionPane.showMessageDialog(null, "CLIENTE REMOVIDO COM SUCESSO!", "Sucesso",
                JOptionPane.INFORMATION_MESSAGE);
        this.dispose();
    }//GEN-LAST:event_btnDeletarClienteProcuradoActionPerformed

    private boolean verificarCPf() {
        String cpf = txtCpfProcurado.getText();
        StringBuffer cpfaux = new StringBuffer("");
        String cpfval = cpf;
        try {
            if (cpfval != null) {
                for (int i = 0; i < cpfval.length(); i++) {
                    if (cpfval.charAt(i) != '.') {
                        if (cpfval.charAt(i) != '-') {
                            cpfaux.append(cpfval.charAt(i));
                        }
                    }
                }
            }
        } catch (Exception e) {
        }
        String cpfiguais = cpfaux.toString();
        if ((cpfiguais.equals("00000000000")) || (cpfiguais.equals("11111111111"))
                || (cpfiguais.equals("22222222222")) || (cpfiguais.equals("33333333333"))
                || (cpfiguais.equals("44444444444")) || (cpfiguais.equals("55555555555"))
                || (cpfiguais.equals("66666666666")) || (cpfiguais.equals("77777777777"))
                || (cpfiguais.equals("88888888888")) || (cpfiguais.equals("99999999999"))
                || ((cpfiguais.length() != 11))) {
            return (false);

        } else {
            char dig10, dig11;
            int sm, i, r, num, peso;
            // "try" - protege o codigo para eventuais erros de conversao de tipo (int)
            try {
                // Calculo do 1o. Digito Verificador
                sm = 0;
                peso = 10;

                for (i = 0; i < 9; i++) {
                    // converte o i-esimo caractere do CPF em um numero: 
                    // por exemplo, transforma o caractere '0' no inteiro 0 
                    // (48 eh a posicao de '0' na tabela ASCII) 
                    num = (int) (cpfaux.charAt(i) - 48);
                    sm = sm + (num * peso);
                    peso = peso - 1;
                }
                r = 11 - (sm % 11);
                if ((r == 10) || (r == 11))
                    dig10 = '0';
                else
                    dig10 = (char) (r + 48);
                // converte no respectivo caractere numerico 
                // Calculo do 2o. Digito Verificador 
                sm = 0;
                peso = 11;
                for (i = 0; i < 10; i++) {
                    num = (int) (cpfaux.charAt(i) - 48);
                    sm = sm + (num * peso);
                    peso = peso - 1;
                }
                r = 11 - (sm % 11);
                if ((r == 10) || (r == 11))
                    dig11 = '0';
                else
                    dig11 = (char) (r + 48);
                // Verifica se os digitos calculados conferem com os digitos informados. 
                if ((dig10 == cpfaux.charAt(9)) && (dig11 == cpfaux.charAt(10))) {
                    return (true);
                } else {
                    return (false);
                }
            } catch (InputMismatchException erro) {
                return (false);
            }
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAlterarClienteProcurado;
    private javax.swing.JButton btnCancelarClienteProcurado;
    private javax.swing.JButton btnDeletarClienteProcurado;
    private javax.swing.JComboBox cbxSexoProcurado;
    private javax.swing.JLabel lblCpfProcurado;
    private javax.swing.JLabel lblCpfValido;
    private javax.swing.JLabel lblIDClienteProcurado;
    private javax.swing.JLabel lblIdadeProcurado;
    private javax.swing.JLabel lblNomeClienteProcurado;
    private javax.swing.JLabel lblSexoProcurado;
    private javax.swing.JLabel lblTelefoneProcurado;
    private javax.swing.JFormattedTextField txtCpfProcurado;
    private javax.swing.JFormattedTextField txtFoneProcurado;
    private javax.swing.JTextField txtIdClienteProcurado;
    private javax.swing.JTextField txtIdadeProcurado;
    private javax.swing.JTextField txtNomeClienteProcurado;
    // End of variables declaration//GEN-END:variables
}