How do I clean a JTable?

-1

I'm using JPA to populate my table which is located at Jframe .

Through JPA, I make a selection in my bank to find all names that have part of the name I wrote, for example, if the entry is "m", all people with a name beginning with "m" should appear in the my list, if you change to "mi" only those who have the name that begins with these two letters appears, and if the entry is empty, all the clients in the table appear.

So the problem is that I can not clear my table for the next search, it only replaces the rows and the rest is the result of the previous search, I'd like to know how to delete each search.

package br.com.exemplo.telas;

import br.com.exemplo.conexao.JPAUtil;
import br.com.exemplo.entity.Cliente;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.swing.JOptionPane;
//biblioteca rs2xml.jar

/**
 *
 * @author costa
 */
public class TelaConsultar extends javax.swing.JInternalFrame {

    int idtb;
    EntityManager conexao;

    /**
     * Creates new form TelaConsulta
     */
    public TelaConsultar() {
        initComponents();
        conexao = new JPAUtil().getEM();
        pesquisar();
    }

    /**
     * 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() {

        jScrollPane2 = new javax.swing.JScrollPane();
        tblClientes = new javax.swing.JTable();
        txtCliPes = new javax.swing.JTextField();
        txtConId = new javax.swing.JTextField();
        btnRemove = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setTitle("Consulta");
        setPreferredSize(new java.awt.Dimension(640, 480));

        tblClientes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblClientes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblClientesMouseClicked(evt);
            }
        });
        jScrollPane2.setViewportView(tblClientes);

        txtCliPes.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txtCliPesKeyReleased(evt);
            }
        });

        txtConId.setEnabled(false);
        txtConId.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtConIdActionPerformed(evt);
            }
        });

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

        jButton2.setText("Edita Cliente");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(txtCliPes, javax.swing.GroupLayout.PREFERRED_SIZE, 259, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(60, 60, 60)
                        .addComponent(txtConId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 594, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(21, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton2)
                .addGap(73, 73, 73)
                .addComponent(btnRemove)
                .addGap(221, 221, 221))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtCliPes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtConId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(94, 94, 94)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnRemove)
                    .addComponent(jButton2))
                .addGap(67, 67, 67))
        );

        setBounds(0, 0, 641, 480);
    }// </editor-fold>                        
    // O evento abaixo e do tipo "enquanto vou pesquisando"
    private void txtCliPesKeyReleased(java.awt.event.KeyEvent evt) {                                      
        pesquisar();
    }                                     
     //Enveto que serar usado para setar os campos da tabela clicando com o mouse
    private void tblClientesMouseClicked(java.awt.event.MouseEvent evt) {                                         
        int setar = tblClientes.getSelectedRow();
        System.out.println(tblClientes.getModel().getValueAt(setar, 0).toString());
        idtb = Integer.parseInt(tblClientes.getModel().getValueAt(setar, 0).toString());
        //Abre o form TelaCliente

        /*try {
            int setar = tblClientes.getSelectedRow();
            String id = tblClientes.getModel().getValueAt(setar, 0).toString();
            TelaAterar tela = new TelaAterar();
            tela.setVisible(true);
            tela.setarCampos(id);
        TelaPrincipal desc = new TelaPrincipal();
        desc.desktop.add(tela);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }*/

    }                                        

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

    private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {                                          
        int sair =JOptionPane.
                showConfirmDialog(null, "Tem certeza que deseja apagar?", "Atenção",
                        JOptionPane.YES_NO_OPTION);  
        if (sair == JOptionPane.YES_OPTION) {
            deletar();

        }

    }                                         

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        TelaAterar tele = new TelaAterar();
        TelaPrincipal tela = new TelaPrincipal();
        tele.setVisible(true);
        tela.desktop.add(tele);

    }                                        


    // Variables declaration - do not modify                     
    private javax.swing.JButton btnRemove;
    private javax.swing.JButton jButton2;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable tblClientes;
    private javax.swing.JTextField txtCliPes;
    private javax.swing.JTextField txtConId;
    // End of variables declaration                   

    //Metodo para setar os campos do formulario com o conteudo da tabela
    private void pesquisar() {

        conexao.getTransaction().begin();


        //limpaTabela();
        String jpql = ("select c from Cliente c where c.nome like  :cNome");

        Query query = conexao.createQuery(jpql);
        query.setParameter("cNome", txtCliPes.getText() + "%");

        List<Cliente> cliente = query.getResultList();
        int i = 0;

        for (Cliente cli : cliente) {

            tblClientes.setValueAt(cli.getId(), i, 0);
            i++;
        }

        conexao.getTransaction().commit();

        //Usar a Biblioteca rs2xlm.jar para preencher a tabela
        //      tblClientes.setModel(DbUtils.resultSetToTableModel(rs));
    }



    private void deletar() {
       conexao.getTransaction().begin();

       Cliente cli =conexao.find(Cliente.class, idtb);
       conexao.remove(cli);

        conexao.getTransaction().commit();
    }

}
    
asked by anonymous 20.06.2017 / 19:48

1 answer

2

If you are using DefaultTableModel the command below already resolves:

((DefaultTableModel) suaTable.getModel()).setRowCount(0);

According to documentation , the setRowCount method defines the number of rows that the default model should have, if the defined size is less than the current row size, excess rows are discarded.

Just put it at the beginning of your search method, replacing suaTable with the correct variable of your JTable .

By adapting to the search code, you should also change how you add the items, as the above method will zero the list of DefaultTableModel objects, and using setValueAt will pop ArrayOfBoundException . Add new lines using addRow :

private void pesquisar() {

    conexao.getTransaction().begin();


    //limpaTabela
    ((DefaultTableModel) suaTable.getModel()).setRowCount(0);

    String jpql = ("select c from Cliente c where c.nome like  :cNome");

    Query query = conexao.createQuery(jpql);
    query.setParameter("cNome", txtCliPes.getText() + "%");

    List<Cliente> cliente = query.getResultList();

    for (Cliente cli : cliente) {

        tblClientes.addRow(new Object[]{cli.getId()});
    }

    conexao.getTransaction().commit();

    //Usar a Biblioteca rs2xlm.jar para preencher a tabela
    //      tblClientes.setModel(DbUtils.resultSetToTableModel(rs));
}
    
20.06.2017 / 19:50