Cadastro de Clientes com GUI e MySQL

Publicado por Alex Inocencio Santos (última atualização em 04/05/2015)

[ Hits: 12.974 ]

Download JavaApplicationCadastroCliente.zip




Este script possui uma GUI criada no NetBeans 8.0.2 com conexão ao banco de dados MySQL.

  



Esconder código-fonte

/*
 * 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 apresentação;

import controle.Cliente;
import controle.Compra;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.swing.JOptionPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 *
 * @author alex
 */
public class JFrameClientes extends javax.swing.JFrame {

    /**
     * Creates new form JFrameClientes
     */
    public JFrameClientes() {
        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() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        JavaApplicationCadastroClientePUEntityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("JavaApplicationCadastroClientePU").createEntityManager();
        clienteQuery = java.beans.Beans.isDesignTime() ? null : JavaApplicationCadastroClientePUEntityManager.createQuery("SELECT c FROM Cliente c");
        clienteList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(clienteQuery.getResultList());
        compraQuery = java.beans.Beans.isDesignTime() ? null : JavaApplicationCadastroClientePUEntityManager.createQuery("SELECT c FROM Compra c");
        compraList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(compraQuery.getResultList());
        jTabbedPaneCliente = new javax.swing.JTabbedPane();
        jPanelCliente = new javax.swing.JPanel();
        jLabelId = new javax.swing.JLabel();
        jLabelNome = new javax.swing.JLabel();
        jLabelCpf = new javax.swing.JLabel();
        jLabelEndereco = new javax.swing.JLabel();
        jLabelCidade = new javax.swing.JLabel();
        jLabelEstado = new javax.swing.JLabel();
        jTextFieldId = new javax.swing.JTextField();
        jTextFieldNome = new javax.swing.JTextField();
        jTextFieldCPF = new javax.swing.JTextField();
        jTextFieldEndereco = new javax.swing.JTextField();
        jTextFieldCidade = new javax.swing.JTextField();
        jTextFieldEstado = new javax.swing.JTextField();
        jButtonInserirCliente = new javax.swing.JButton();
        jButtonSalvarCliente = new javax.swing.JButton();
        jButtonCancelarCliente = new javax.swing.JButton();
        jButtonExcluirCliente = new javax.swing.JButton();
        jLabelCpfBusca = new javax.swing.JLabel();
        jTextFieldCpfBusca = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableClientes = new javax.swing.JTable();
        jTextFieldCPFBusca = new javax.swing.JButton();
        jPanelCompras = new javax.swing.JPanel();
        jLabelIDCompra = new javax.swing.JLabel();
        jLabelData = new javax.swing.JLabel();
        jLabelDescricao = new javax.swing.JLabel();
        jLabelQtd = new javax.swing.JLabel();
        jLabelValorUnitario = new javax.swing.JLabel();
        jTextFieldCompraId = new javax.swing.JTextField();
        jFormattedTextFieldCompraData = new javax.swing.JFormattedTextField();
        jFormattedTextFieldCompraQtd = new javax.swing.JFormattedTextField();
        jFormattedTextFieldCompraPrcUnitario = new javax.swing.JFormattedTextField();
        jTextFieldCompraDescricao = new javax.swing.JTextField();
        jButtonCompraInserir = new javax.swing.JButton();
        jButtonCompraSalvar = new javax.swing.JButton();
        jButtonCompraCancelar = new javax.swing.JButton();
        jButtonCompraExcluir = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTableCompras = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jTabbedPaneCliente.setTabLayoutPolicy(javax.swing.JTabbedPane.SCROLL_TAB_LAYOUT);

        jLabelId.setText("Id");

        jLabelNome.setText("Nome");

        jLabelCpf.setText("Cpf");

        jLabelEndereco.setText("Endereço");

        jLabelCidade.setText("Cidade");

        jLabelEstado.setText("Estado");

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jTableClientes, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.id}"), jTextFieldId, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jTextFieldId.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldIdActionPerformed(evt);
            }
        });

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jTableClientes, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.nome}"), jTextFieldNome, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jTextFieldNome.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldNomeActionPerformed(evt);
            }
        });
        jTextFieldNome.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTextFieldNomeKeyPressed(evt);
            }
        });

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jTableClientes, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.cpf}"), jTextFieldCPF, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jTableClientes, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.endereco}"), jTextFieldEndereco, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jTableClientes, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.cidade}"), jTextFieldCidade, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jTableClientes, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.estado}"), jTextFieldEstado, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jButtonInserirCliente.setText("Inserir");
        jButtonInserirCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonInserirClienteActionPerformed(evt);
            }
        });

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

        jButtonCancelarCliente.setText("Cancelar");
        jButtonCancelarCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelarClienteActionPerformed(evt);
            }
        });

        jButtonExcluirCliente.setText("Excluir");
        jButtonExcluirCliente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonExcluirClienteActionPerformed(evt);
            }
        });

        jLabelCpfBusca.setText("Cpf Busca");

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, clienteList, jTableClientes);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${id}"));
        columnBinding.setColumnName("Id");
        columnBinding.setColumnClass(Long.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${nome}"));
        columnBinding.setColumnName("Nome");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${cpf}"));
        columnBinding.setColumnName("Cpf");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${endereco}"));
        columnBinding.setColumnName("Endereco");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${cidade}"));
        columnBinding.setColumnName("Cidade");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${estado}"));
        columnBinding.setColumnName("Estado");
        columnBinding.setColumnClass(String.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();

        jTableClientes.getSelectionModel () .addListSelectionListener(new ListSelectionListener() { // Adiciona um evento de mudança de seleção ao jTabelClientes

            public void valueChanged(ListSelectionEvent e) { // Evento de mudança de seleção
                if (jTextFieldId.getText().isEmpty()) { // Não há cliente selecionado (Não há o que mostrar)
                    compraQuery = JavaApplicationCadastroClientePUEntityManager.createQuery("SELECT c FROM Compra c WHERE c.idCliente.id=0"); // Gerar uma query compra vazia
                } else {
                    compraQuery = JavaApplicationCadastroClientePUEntityManager.createQuery("SELECT c FROM Compra c WHERE c.idCliente.id=" + jTextFieldId.getText()); // Buscar compras de cliente Id
                }
                compraList.clear(); // Limpa compras atual
                compraList.addAll(compraQuery.getResultList()); // Adiciona ao list as compras buscadas
                if (jTableCompras.getRowCount() > 0) { // Existe compras
                    jTableCompras.setRowSelectionInterval(0, 0); // Seleciona a primeira no jTable
                } else {
                    // Limpa campos da guia compras se elas não existem
                    jTextFieldCompraDescricao.setText(null);
                    jTextFieldCompraId.setText(null);
                    jFormattedTextFieldCompraData.setText(null);
                    jFormattedTextFieldCompraPrcUnitario.setText(null);
                    jFormattedTextFieldCompraQtd.setText(null);
                }
            }
        }

    );
    jScrollPane1.setViewportView(jTableClientes);

    jTextFieldCPFBusca.setText("Buscar");
    jTextFieldCPFBusca.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jTextFieldCPFBuscaActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout jPanelClienteLayout = new javax.swing.GroupLayout(jPanelCliente);
    jPanelCliente.setLayout(jPanelClienteLayout);
    jPanelClienteLayout.setHorizontalGroup(
        jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanelClienteLayout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabelId)
                .addComponent(jLabelNome)
                .addComponent(jLabelCpf)
                .addComponent(jLabelEndereco)
                .addComponent(jLabelCidade)
                .addComponent(jLabelEstado))
            .addGap(55, 55, 55)
            .addGroup(jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addComponent(jTextFieldEstado, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)
                .addComponent(jTextFieldCidade)
                .addComponent(jTextFieldEndereco)
                .addComponent(jTextFieldNome)
                .addComponent(jTextFieldId)
                .addComponent(jTextFieldCPF))
            .addGap(18, 18, 18)
            .addGroup(jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                .addComponent(jButtonSalvarCliente, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButtonCancelarCliente, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButtonExcluirCliente, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButtonInserirCliente, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGap(33, 33, 33)
            .addComponent(jLabelCpfBusca)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jTextFieldCpfBusca)
                .addGroup(jPanelClienteLayout.createSequentialGroup()
                    .addComponent(jTextFieldCPFBusca)
                    .addGap(0, 0, Short.MAX_VALUE))))
        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 601, Short.MAX_VALUE)
    );
    jPanelClienteLayout.setVerticalGroup(
        jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanelClienteLayout.createSequentialGroup()
            .addGap(26, 26, 26)
            .addGroup(jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabelId)
                .addComponent(jTextFieldId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButtonInserirCliente)
                .addComponent(jLabelCpfBusca)
                .addComponent(jTextFieldCpfBusca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGroup(jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanelClienteLayout.createSequentialGroup()
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextFieldNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButtonSalvarCliente))
                        .addComponent(jLabelNome)))
                .addGroup(jPanelClienteLayout.createSequentialGroup()
                    .addGap(20, 20, 20)
                    .addComponent(jTextFieldCPFBusca)))
            .addGap(18, 18, 18)
            .addGroup(jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldCPF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonCancelarCliente))
                .addComponent(jLabelCpf))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabelEndereco)
                .addGroup(jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonExcluirCliente)))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabelCidade)
                .addComponent(jTextFieldCidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jPanelClienteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabelEstado)
                .addComponent(jTextFieldEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(30, 30, 30)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 103, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    jTabbedPaneCliente.addTab("Cliente", jPanelCliente);

    jLabelIDCompra.setText("Id");

    jLabelData.setText("Data");

    jLabelDescricao.setText("Descrição");

    jLabelQtd.setText("Qtd");

    jLabelValorUnitario.setText("Valor Unitário");

    binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jTableCompras, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.id}"), jTextFieldCompraId, org.jdesktop.beansbinding.BeanProperty.create("text"));
    bindingGroup.addBinding(binding);

    jFormattedTextFieldCompraData.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter()));

    binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jTableCompras, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.data}"), jFormattedTextFieldCompraData, org.jdesktop.beansbinding.BeanProperty.create("value"));
    bindingGroup.addBinding(binding);

    jFormattedTextFieldCompraData.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jFormattedTextFieldCompraDataActionPerformed(evt);
        }
    });

    jFormattedTextFieldCompraQtd.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0"))));

    binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jTableCompras, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.qtde}"), jFormattedTextFieldCompraQtd, org.jdesktop.beansbinding.BeanProperty.create("value"));
    bindingGroup.addBinding(binding);

    jFormattedTextFieldCompraPrcUnitario.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter()));

    binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jTableCompras, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.precoUnitario}"), jFormattedTextFieldCompraPrcUnitario, org.jdesktop.beansbinding.BeanProperty.create("value"));
    bindingGroup.addBinding(binding);

    binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, jTableCompras, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.descricao}"), jTextFieldCompraDescricao, org.jdesktop.beansbinding.BeanProperty.create("text"));
    bindingGroup.addBinding(binding);

    jTextFieldCompraDescricao.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyPressed(java.awt.event.KeyEvent evt) {
            jTextFieldCompraDescricaoKeyPressed(evt);
        }
    });

    jButtonCompraInserir.setText("Inserir");
    jButtonCompraInserir.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButtonCompraInserirActionPerformed(evt);
        }
    });

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

    jButtonCompraCancelar.setText("Cancelar");
    jButtonCompraCancelar.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButtonCompraCancelarActionPerformed(evt);
        }
    });

    jButtonCompraExcluir.setText("Excluir");
    jButtonCompraExcluir.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButtonCompraExcluirActionPerformed(evt);
        }
    });

    jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, compraList, jTableCompras);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${id}"));
    columnBinding.setColumnName("Id");
    columnBinding.setColumnClass(Long.class);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${data}"));
    columnBinding.setColumnName("Data");
    columnBinding.setColumnClass(java.util.Date.class);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${descricao}"));
    columnBinding.setColumnName("Descricao");
    columnBinding.setColumnClass(String.class);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${qtde}"));
    columnBinding.setColumnName("Qtde");
    columnBinding.setColumnClass(Integer.class);
    columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${precoUnitario}"));
    columnBinding.setColumnName("Preco Unitario");
    columnBinding.setColumnClass(Double.class);
    bindingGroup.addBinding(jTableBinding);
    jTableBinding.bind();

    jScrollPane2.setViewportView(jTableCompras);

    javax.swing.GroupLayout jPanelComprasLayout = new javax.swing.GroupLayout(jPanelCompras);
    jPanelCompras.setLayout(jPanelComprasLayout);
    jPanelComprasLayout.setHorizontalGroup(
        jPanelComprasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanelComprasLayout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanelComprasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 577, Short.MAX_VALUE)
                .addGroup(jPanelComprasLayout.createSequentialGroup()
                    .addGroup(jPanelComprasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabelIDCompra)
                        .addComponent(jLabelData)
                        .addComponent(jLabelQtd)
                        .addComponent(jLabelValorUnitario)
                        .addComponent(jLabelDescricao))
                    .addGap(36, 36, 36)
                    .addGroup(jPanelComprasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jFormattedTextFieldCompraPrcUnitario, javax.swing.GroupLayout.DEFAULT_SIZE, 263, Short.MAX_VALUE)
                        .addComponent(jFormattedTextFieldCompraQtd)
                        .addComponent(jFormattedTextFieldCompraData)
                        .addComponent(jTextFieldCompraId)
                        .addComponent(jTextFieldCompraDescricao))
                    .addGap(35, 35, 35)
                    .addGroup(jPanelComprasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(jButtonCompraSalvar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButtonCompraCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButtonCompraExcluir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButtonCompraInserir, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGap(0, 0, Short.MAX_VALUE)))
            .addContainerGap())
    );
    jPanelComprasLayout.setVerticalGroup(
        jPanelComprasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanelComprasLayout.createSequentialGroup()
            .addGap(27, 27, 27)
            .addGroup(jPanelComprasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabelIDCompra)
                .addComponent(jTextFieldCompraId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButtonCompraInserir))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(jPanelComprasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabelData)
                .addGroup(jPanelComprasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jFormattedTextFieldCompraData, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButtonCompraSalvar)))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(jPanelComprasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanelComprasLayout.createSequentialGroup()
                    .addGroup(jPanelComprasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jLabelDescricao)
                        .addComponent(jTextFieldCompraDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanelComprasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabelQtd)
                        .addComponent(jFormattedTextFieldCompraQtd, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(jPanelComprasLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabelValorUnitario)
                        .addComponent(jFormattedTextFieldCompraPrcUnitario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGroup(jPanelComprasLayout.createSequentialGroup()
                    .addComponent(jButtonCompraCancelar)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(jButtonCompraExcluir)))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(90, Short.MAX_VALUE))
    );

    jTabbedPaneCliente.addTab("Compras", jPanelCompras);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jTabbedPaneCliente)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jTabbedPaneCliente)
    );

    bindingGroup.bind();

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

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

    private void formWindowOpened(java.awt.event.WindowEvent evt) {
        // TODO add your handling code here:
        this.configurarClienteInicializacao();
    }

    private void jButtonInserirClienteActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:// Código para inserir o cliente
        this.inserirCliente();
    }
 /*
    private void jButtonSalvarClienteActionPerformed(java.awt.event.ActionEvent evt) {
        // Código para salvar o cliente
        try {
            if (this.estadoCliente == EstadoCliente.INSERINDO_CLIENTE) {
                this.salvarClienteEmInsercao();
            } else {
                this.salvarClienteEmAtualização();
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, e);
        }
            JOptionPane.showMessageDialog(null,"Cadastro Efetuado!!");*//*
    }
*/
    private void jButtonCancelarClienteActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
         // Código para cancelar alteração ou inserção de cliente
        try {
            if (this.estadoCliente == EstadoCliente.INSERINDO_CLIENTE) {
                this.cancelarInsercaoCliente();
            } else {
                this.cancelarAtualizacaoCliente();
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, e);
        }
    }

    private void jButtonExcluirClienteActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
             // Código para excluir o cliente
        if (JOptionPane.showConfirmDialog(rootPane, "Confirma a exclusão deste registro?") == JOptionPane.OK_OPTION) {
            try {
                this.excluirCliente();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(rootPane, e);
            }
        }
    }

    private void jTextFieldCPFBuscaActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        // código para encontrar cliente
        this.encontrarCliente(this.jTextFieldCPFBusca.getText());
    }

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

    private void jTextFieldNomeActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
             // Código que provoca edição de cliente em modificação no campo Nome
        this.configurarMudancaDeEstadoPorEdicaoCliente();
    }

    private void jButtonCompraExcluirActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
           // Código para exclusão de compra
        if (JOptionPane.showConfirmDialog(rootPane, "Confirma a exclusão deste registro?") == JOptionPane.OK_OPTION) {
            try {
                this.excluirCompra();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(rootPane, e);
            }
        }
    }

    private void jTextFieldNomeKeyPressed(java.awt.event.KeyEvent evt) {
        // TODO add your handling code here:
        // Edição de cliente por alteração do campo Nome
        this.configurarMudancaDeEstadoPorEdicaoCliente();
    }

    private void jTextFieldCompraDescricaoKeyPressed(java.awt.event.KeyEvent evt) {
        // TODO add your handling code here:
         // Código para colocar em edição a compra por alteração do campo descrição
        this.configurarMudancaDeEstadoPorEdicaoCompra();
    }

    private void jButtonCompraCancelarActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
         // Código que cancela inserção ou edição de compra
        try {
            if (this.estadoCompra == EstadoCompra.INSERINDO_COMPRA) {
                this.cancelarInsercaoCompra();
            } else {
                this.cancelarAtualizacaoCompra();
            }

        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, e);
        }
    }

    private void jButtonCompraSalvarActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
         // Código para salvar compra
        try {

            if (this.estadoCompra == EstadoCompra.INSERINDO_COMPRA) {

                this.salvarCompraEmInsercao();
            } else {
                this.salvarCompraEmAtualizacao();
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, e);
        }
    }

    private void jButtonCompraInserirActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
         // Código para inserir compra
        this.inserirCompra();
    }

    private void jButtonSalvarClienteActionPerformed(java.awt.event.ActionEvent evt) {
        // Código para salvar o cliente
        try {
            if (this.estadoCliente == EstadoCliente.INSERINDO_CLIENTE) {
                this.salvarClienteEmInsercao();
            } else {
                this.salvarClienteEmAtualização();
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, e);
        }
    }

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

    private void jButtonInserirClienteActionPerformed(Object object) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }
    private enum EstadoCliente {

        INSERINDO_CLIENTE,
        EDITANDO_CLIENTE,
        CONSULTANDO_CLIENTE
    }

    private enum EstadoCompra {

        INSERINDO_COMPRA,
        EDITANDO_COMPRA,
        CONSULTANDO_COMPRA
    }
    private EstadoCliente estadoCliente = EstadoCliente.CONSULTANDO_CLIENTE;
    private EstadoCompra estadoCompra = EstadoCompra.CONSULTANDO_COMPRA;
    private Cliente cliente;

    public Cliente getCliente() {
        return cliente;
    }

    public void setCliente(Cliente cliente) {
        this.cliente = cliente;
    }

    private void inserirCliente() {
        Cliente cliente = new Cliente();
        this.clienteList.add(cliente); // Insere no clienteList para forçar a aparição de uma linha em branco no JTableClientes

        // Seleciona objeto inserido na tabela e estabelece foco no campo "nome" (Apenas dar a sensação de inserção)
        this.jTableClientes.setRowSelectionInterval(this.jTableClientes.getRowCount() - 1, this.jTableClientes.getRowCount() - 1);
        this.jTextFieldNome.requestFocus();

        //Configura botões para estado de Inserção
        this.jButtonInserirCliente.setEnabled(false);
        this.jButtonExcluirCliente.setEnabled(false);
        this.jButtonCancelarCliente.setEnabled(true);
        this.jButtonSalvarCliente.setEnabled(true);

        this.estadoCliente = EstadoCliente.INSERINDO_CLIENTE;
    }

    private void salvarClienteEmAtualização() {
        // Encontra e carrega o objeto de atualização com base no "Id"
        if (cliente.encontradoId(Long.valueOf(this.jTextFieldId.getText()))) {

            // Atualiza o objeto com novos valores
            cliente.setNome(this.jTextFieldNome.getText());
            cliente.setCidade(this.jTextFieldCidade.getText());
            cliente.setCpf(this.jTextFieldCPF.getText());
            cliente.setEndereco(this.jTextFieldEndereco.getText());
            cliente.setEstado(this.jTextFieldEstado.getText());

            if (cliente.atualizado()) { // Se atualizado objeto no BD

                //Configura botões para estado de Consulta
                this.jButtonInserirCliente.setEnabled(true);
                this.jButtonExcluirCliente.setEnabled(this.jTableClientes.getRowCount() != 0); // Existe algo para excluir?
                this.jButtonCancelarCliente.setEnabled(false);
                this.jButtonSalvarCliente.setEnabled(false);

                this.estadoCliente = EstadoCliente.CONSULTANDO_CLIENTE;
            }
        }
    }

    private void encontrarCliente(String CPF) {
        // Encontra e carrega o objeto de atualização com base no "Id"
        if (CPF.isEmpty()) {

            // Busca todos
            clienteQuery = JavaApplicationCadastroClientePUEntityManager.createQuery("SELECT c FROM Cliente c");

        } else {

            clienteQuery = JavaApplicationCadastroClientePUEntityManager.createQuery("SELECT c FROM Cliente c WHERE c.cpf = " + CPF);
        }

        clienteList.clear();
        clienteList.addAll(clienteQuery.getResultList());
        if (jTableClientes.getRowCount() > 0) {
            jTableClientes.setRowSelectionInterval(0, 0);
        } else {
            jTextFieldNome.setText(null);
            jTextFieldId.setText(null);
            jTextFieldCPF.setText(null);
            jTextFieldEndereco.setText(null);
            jTextFieldCidade.setText(null);
            jTextFieldEstado.setText(null);
        }
    }

    private void salvarClienteEmInsercao() {
        // Cria o objeto
        Cliente cliente = new Cliente();

        // Configura o objeto com os valores definidos nos campos
        cliente.setNome(this.jTextFieldNome.getText());
        cliente.setCidade(this.jTextFieldCidade.getText());
        cliente.setCpf(this.jTextFieldCPF.getText());
        cliente.setEndereco(this.jTextFieldEndereco.getText());
        cliente.setEstado(this.jTextFieldEstado.getText());

        if (cliente.armazenado()) { // Se armazenado objeto no BD

            // Retira a linha em branco, selecionada na inserção, da lista e do JTableClientes
            this.clienteList.remove(this.jTableClientes.getSelectedRow());
            // Adiciona o novo "Cliente" gravado no BD, na lista e automaticamente no JTableClientes.
            this.clienteList.add(cliente);

            // Seleciona o último da lista
            this.jTableClientes.setRowSelectionInterval(this.jTableClientes.getRowCount() - 1, this.jTableClientes.getRowCount() - 1);

            //Configura botões para estado de Consulta
            this.jButtonInserirCliente.setEnabled(true);
            this.jButtonExcluirCliente.setEnabled(this.jTableClientes.getRowCount() != 0); // Existe algo para excluir?
            this.jButtonCancelarCliente.setEnabled(false);
            this.jButtonSalvarCliente.setEnabled(false);

            this.estadoCliente = EstadoCliente.CONSULTANDO_CLIENTE;
        }

    }

    private void cancelarInsercaoCliente() {

        // Remove a linha em branco da lista e automaticamente do JTable
        this.clienteList.remove(this.jTableClientes.getSelectedRow());
        if (this.jTableClientes.getRowCount() > 0) { // Se houver objetos na lista
            // Seleciona o último da lista
            this.jTableClientes.setRowSelectionInterval(this.jTableClientes.getRowCount() - 1, this.jTableClientes.getRowCount() - 1);
        }

        //Configura botões para estado de Consulta
        this.jButtonInserirCliente.setEnabled(true);
        this.jButtonExcluirCliente.setEnabled(this.jTableClientes.getRowCount() != 0); // Existe algo para excluir?
        this.jButtonCancelarCliente.setEnabled(false);
        this.jButtonSalvarCliente.setEnabled(false);

        this.estadoCliente = EstadoCliente.CONSULTANDO_CLIENTE;

    }

    private void cancelarAtualizacaoCliente() {
        // Busca o objeto com informações anteriores à atualização
        Cliente cliente = new Cliente();
        if (cliente.encontradoId(Long.valueOf(this.jTextFieldId.getText()))) {

            // Atualiza os campos com dados sem alteração
            this.jTextFieldNome.setText(cliente.getNome());
            this.jTextFieldCidade.setText(cliente.getCidade());
            this.jTextFieldCPF.setText(cliente.getCpf());
            this.jTextFieldEndereco.setText(cliente.getEndereco());
            this.jTextFieldEstado.setText(cliente.getEstado());
        }

        //Configura botões para estado de Consulta
        this.jButtonInserirCliente.setEnabled(true);
        this.jButtonExcluirCliente.setEnabled(this.jTableClientes.getRowCount() != 0); // Existe algo para excluir?
        this.jButtonCancelarCliente.setEnabled(false);
        this.jButtonSalvarCliente.setEnabled(false);

        this.estadoCliente = EstadoCliente.CONSULTANDO_CLIENTE;

    }

    private void excluirCliente() {
        Cliente cliente = new Cliente(); // Cria o objeto
        cliente.setId(Long.valueOf(this.jTextFieldId.getText())); // Configura o id de exclusão
        if (cliente.desarmazenado()) { // Exclui o objeto do BD
            int linhaSelecionada = this.jTableClientes.getSelectedRow(); // Marca linha selecionada da tabela
            this.clienteList.remove(this.jTableClientes.getSelectedRow()); // Remove objeto da lista e do JTabel
            if (this.jTableClientes.getRowCount() > 0) { // Se houver linhas na tabela
                if (linhaSelecionada > 0) {
                    linhaSelecionada--;
                }
                this.jTableClientes.setRowSelectionInterval(linhaSelecionada, linhaSelecionada); // Seleciona linha marcada
            }

            //Configura botões para estado de Consulta
            this.jButtonInserirCliente.setEnabled(true);
            this.jButtonExcluirCliente.setEnabled(this.jTableClientes.getRowCount() != 0); // Existe algo para excluir?
            this.jButtonCancelarCliente.setEnabled(false);
            this.jButtonSalvarCliente.setEnabled(false);

            this.estadoCliente = EstadoCliente.CONSULTANDO_CLIENTE;

        }
    }

    private void configurarMudancaDeEstadoPorEdicaoCliente() {

        //Configura botões para Estado de Edição
        this.jButtonInserirCliente.setEnabled(false);
        this.jButtonExcluirCliente.setEnabled(false);
        this.jButtonCancelarCliente.setEnabled(true);
        this.jButtonSalvarCliente.setEnabled(true);

        if (this.estadoCliente == EstadoCliente.CONSULTANDO_CLIENTE) {
            if (this.jTableClientes.getRowCount() != 0) { // Existe algo para editar?
                this.estadoCliente = EstadoCliente.EDITANDO_CLIENTE;
            } else {
                this.jButtonInserirClienteActionPerformed(null); // Executa uma inserção
            }
        }
    }

    private void configurarClienteInicializacao() {
        // Configuração da Guia Clientes
        if (this.jTableClientes.getRowCount() > 0) { // Se houver linhas na lista
            this.jTableClientes.setRowSelectionInterval(0, 0); // Seleciona linha 0 (primeira)
        }

        //Configura botões para estado de Consulta
        this.jButtonInserirCliente.setEnabled(true);
        this.jButtonExcluirCliente.setEnabled(this.jTableClientes.getRowCount() != 0); // Existe algo para excluir?
        this.jButtonCancelarCliente.setEnabled(false);
        this.jButtonSalvarCliente.setEnabled(false);


        // Configuração da Guia Compras
        if (this.jTableCompras.getRowCount() > 0) { // Se houver linhas na lista
            this.jTableCompras.setRowSelectionInterval(0, 0); // Seleciona linha 0 (primeira)
        }

        //Configura botões para o Estado de Consulta
        this.jButtonCompraInserir.setEnabled(true);
        this.jButtonCompraExcluir.setEnabled(this.jTableCompras.getRowCount() != 0); // Existe registro para excluir?
        this.jButtonCompraCancelar.setEnabled(false);
        this.jButtonCompraSalvar.setEnabled(false);
        this.estadoCompra = EstadoCompra.CONSULTANDO_COMPRA;

    }


    private void excluirCompra() {
        Compra compra = new Compra(); // Cria o objeto
        compra.setId(Long.valueOf(this.jTextFieldCompraId.getText())); // Configura o id de exclusão
        if (compra.desarmazenado()) { // Exclui o objeto do BD
            int linhaSelecionada = this.jTableCompras.getSelectedRow(); // Marca linha selecionada da tabela
            this.compraList.remove(this.jTableCompras.getSelectedRow()); // Remove objeto da lista
            if (this.jTableCompras.getRowCount() > 0) { // Se houver linhas na tabela
                if (linhaSelecionada > 0) {
                    linhaSelecionada--;
                }
                this.jTableCompras.setRowSelectionInterval(linhaSelecionada, linhaSelecionada); // Seleciona linha marcada
            }

            //Configura botões para o Estado de Consulta
            this.jButtonCompraInserir.setEnabled(true);
            this.jButtonCompraExcluir.setEnabled(this.jTableCompras.getRowCount() != 0); // Existe algo para excluir?
            this.jButtonCompraCancelar.setEnabled(false);
            this.jButtonCompraSalvar.setEnabled(false);

            this.estadoCompra = EstadoCompra.CONSULTANDO_COMPRA;

        }
    }

    private void configurarMudancaDeEstadoPorEdicaoCompra() {

        //Configura botões para Estado de Edição
        this.jButtonCompraInserir.setEnabled(false);
        this.jButtonCompraExcluir.setEnabled(false);
        this.jButtonCompraCancelar.setEnabled(true);
        this.jButtonCompraSalvar.setEnabled(true);

        if (this.estadoCompra == EstadoCompra.CONSULTANDO_COMPRA) {
            if (this.jTableCompras.getRowCount() != 0) { // Existe algo para editar?
                this.estadoCompra = EstadoCompra.EDITANDO_COMPRA;
            } else {
                this.jButtonInserirClienteActionPerformed(null); // Executa uma inserção
            }
        }
    }

    private void cancelarInsercaoCompra() {

        // Remove a linha em branco da lista e automaticamente do JTable
        this.compraList.remove(this.jTableCompras.getSelectedRow());
        if (this.jTableCompras.getRowCount() > 0) { // Se houver objetos na lista
            // Seleciona o último da lista
            this.jTableCompras.setRowSelectionInterval(this.jTableCompras.getRowCount() - 1, this.jTableCompras.getRowCount() - 1);
        }

    }

    private void cancelarAtualizacaoCompra() {
        // Busca o objeto com informações anteriores à atualização
        Compra compra = new Compra();
        if (compra.encontradoId(Long.valueOf(this.jTextFieldCompraId.getText()))) {

            // Atualiza os campos com dados sem alteração
            this.jTextFieldCompraDescricao.setText(compra.getDescricao());

            this.jFormattedTextFieldCompraData.setText(new SimpleDateFormat("dd/MM/yyyy").format(compra.getData()));
            DecimalFormat decimalFormat = new DecimalFormat("¤ #,##0.00");
            this.jFormattedTextFieldCompraPrcUnitario.setText(decimalFormat.format(compra.getPrecoUnitario()));
            this.jFormattedTextFieldCompraQtd.setText(String.valueOf(compra.getQtde()));
        }

        //Configura botões para o Estado de Consulta
        this.jButtonCompraInserir.setEnabled(true);
        this.jButtonCompraExcluir.setEnabled(this.jTableCompras.getRowCount() != 0); // Existe registro para excluir?
        this.jButtonCompraCancelar.setEnabled(false);
        this.jButtonCompraSalvar.setEnabled(false);
        this.estadoCompra = EstadoCompra.CONSULTANDO_COMPRA;
    }

    private void inserirCompra() {
        Compra compra = new Compra();
        this.compraList.add(compra); // Insere no compraList para forçar a aparição de uma linha em branco no JTableCompras

        // Seleciona objeto inserido na tabela e estabelece foco no campo "nome" (Apenas dar a sensação de inserção)
        this.jTableCompras.setRowSelectionInterval(this.jTableCompras.getRowCount() - 1, this.jTableCompras.getRowCount() - 1);
        this.jTextFieldCompraDescricao.requestFocus();

        //Configura botões para estado de Inserção
        this.jButtonCompraInserir.setEnabled(false);
        this.jButtonCompraExcluir.setEnabled(false);
        this.jButtonCompraCancelar.setEnabled(true);
        this.jButtonCompraSalvar.setEnabled(true);

        this.estadoCompra = EstadoCompra.INSERINDO_COMPRA;
    }

    private void salvarCompraEmInsercao() throws ParseException {
        // Cria e configura o objeto
        Compra compra = new Compra();

        // Configura o objeto com os valores definidos nos campos
        Cliente cliente = new Cliente();
        cliente.encontradoId(Long.valueOf(this.jTextFieldId.getText()));
        compra.setIdCliente(cliente);
        compra.setDescricao(this.jTextFieldCompraDescricao.getText());
        SimpleDateFormat data = new SimpleDateFormat("dd/MM/yyyy");
        compra.setData((java.util.Date) data.parse(this.jFormattedTextFieldCompraData.getText()));
        DecimalFormat decimalFormat = new DecimalFormat("¤ #,##0.00");
        compra.setPrecoUnitario(decimalFormat.parse(this.jFormattedTextFieldCompraPrcUnitario.getText()).doubleValue());

        compra.setQtde(Integer.parseInt(this.jFormattedTextFieldCompraQtd.getText()));

        if (compra.armazenado()) { // Se armazenado objeto no BD

            // Retira o objeto da lista e o adiciona com o id
            this.compraList.remove(this.jTableCompras.getSelectedRow());
            this.compraList.add(compra);

            // Seleciona o último da lista
            this.jTableCompras.setRowSelectionInterval(this.jTableCompras.getRowCount() - 1, this.jTableCompras.getRowCount() - 1);

            // Configura botões em Estado de Consulta
            this.jButtonCompraInserir.setEnabled(true);
            this.jButtonCompraExcluir.setEnabled(this.jTableCompras.getRowCount() != 0); // Existe registro para excluir?
            this.jButtonCompraCancelar.setEnabled(false);
            this.jButtonCompraSalvar.setEnabled(false);

            this.estadoCompra = EstadoCompra.CONSULTANDO_COMPRA;
        }
    }

    private void salvarCompraEmAtualizacao() throws ParseException {

        // Cria e configura o objeto
        Compra compra = new Compra();

        // Encontra e carrega o objeto de atualização
        if (compra.encontradoId(Long.valueOf(this.jTextFieldCompraId.getText()))) {

            // Atualiza o objeto
            compra.setDescricao(this.jTextFieldCompraDescricao.getText());
            SimpleDateFormat data = new SimpleDateFormat("dd/MM/yyyy");
            compra.setData((java.util.Date) data.parse(this.jFormattedTextFieldCompraData.getText()));
            DecimalFormat decimalFormat = new DecimalFormat("¤ #,##0.00");
            compra.setPrecoUnitario(decimalFormat.parse(this.jFormattedTextFieldCompraPrcUnitario.getText()).doubleValue());
            compra.setQtde(Integer.parseInt(this.jFormattedTextFieldCompraQtd.getText()));

            if (compra.atualizado()) { // Se atualizado objeto no BD

                // Configura botões em Estado de Consulta
                this.jButtonCompraInserir.setEnabled(true);
                this.jButtonCompraExcluir.setEnabled(this.jTableCompras.getRowCount() != 0); // Existe registro para excluir?
                this.jButtonCompraCancelar.setEnabled(false);
                this.jButtonCompraSalvar.setEnabled(false);

                this.estadoCompra = EstadoCompra.CONSULTANDO_COMPRA;
            }
        }
    }
    // Variables declaration - do not modify
    private javax.persistence.EntityManager JavaApplicationCadastroClientePUEntityManager;
    private java.util.List<controle.Cliente> clienteList;
    private javax.persistence.Query clienteQuery;
    private java.util.List<controle.Compra> compraList;
    private javax.persistence.Query compraQuery;
    private javax.swing.JButton jButtonCancelarCliente;
    private javax.swing.JButton jButtonCompraCancelar;
    private javax.swing.JButton jButtonCompraExcluir;
    private javax.swing.JButton jButtonCompraInserir;
    private javax.swing.JButton jButtonCompraSalvar;
    private javax.swing.JButton jButtonExcluirCliente;
    private javax.swing.JButton jButtonInserirCliente;
    private javax.swing.JButton jButtonSalvarCliente;
    private javax.swing.JFormattedTextField jFormattedTextFieldCompraData;
    private javax.swing.JFormattedTextField jFormattedTextFieldCompraPrcUnitario;
    private javax.swing.JFormattedTextField jFormattedTextFieldCompraQtd;
    private javax.swing.JLabel jLabelCidade;
    private javax.swing.JLabel jLabelCpf;
    private javax.swing.JLabel jLabelCpfBusca;
    private javax.swing.JLabel jLabelData;
    private javax.swing.JLabel jLabelDescricao;
    private javax.swing.JLabel jLabelEndereco;
    private javax.swing.JLabel jLabelEstado;
    private javax.swing.JLabel jLabelIDCompra;
    private javax.swing.JLabel jLabelId;
    private javax.swing.JLabel jLabelNome;
    private javax.swing.JLabel jLabelQtd;
    private javax.swing.JLabel jLabelValorUnitario;
    private javax.swing.JPanel jPanelCliente;
    private javax.swing.JPanel jPanelCompras;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTabbedPane jTabbedPaneCliente;
    private javax.swing.JTable jTableClientes;
    private javax.swing.JTable jTableCompras;
    private javax.swing.JTextField jTextFieldCPF;
    private javax.swing.JButton jTextFieldCPFBusca;
    private javax.swing.JTextField jTextFieldCidade;
    private javax.swing.JTextField jTextFieldCompraDescricao;
    private javax.swing.JTextField jTextFieldCompraId;
    private javax.swing.JTextField jTextFieldCpfBusca;
    private javax.swing.JTextField jTextFieldEndereco;
    private javax.swing.JTextField jTextFieldEstado;
    private javax.swing.JTextField jTextFieldId;
    private javax.swing.JTextField jTextFieldNome;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration
}

Scripts recomendados

Conexão com Firebird usando a linguagem Java

Conexão com MySQL usando a linguagem Java

SCRIPT CPF

Oracle - Teste de conexão com o banco

a


  

Comentários

Nenhum comentário foi encontrado.


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts