Erro em pesquisar em uma jtable

3 respostas
IFMT

Galera tou fazendo uma pesquisa em uma jtable mas na hora que eu clico no botão naum recebo o resultado…

con_Alunos.executeSQL("select * from "+tabela+" where Nome like'%"+CPPESQUISAR.getText()); preencher_table();

na hora q eu clico no botão quero q ele retorne o resultado na tabela me ajudem…

3 Respostas

ViniGodoy

Onde vc guarda o resultset desse executeSql?

E não seria bom postar o método preencher_table()? Não dá para adivinhar o que você faz lá.

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

/*
 * PesquisaAluno.java
 *
 * Created on 07/04/2011, 12:38:21
 */

package Interface;

import Conexão.Conexao;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Joabe
 */
public class PesquisaAluno extends javax.swing.JFrame {
    private final Conexao con_Alunos;
    private final String tabela;

    /** Creates new form PesquisaAluno */
    public PesquisaAluno() {
        initComponents();
        con_Alunos = new Conexao ();
        con_Alunos.conecta();
        tabela = "CadastroUsuario";
        con_Alunos.executeSQL("select * from "+tabela);
        
    }
     public void preencher_table()
     {
          try
        {
            con_Alunos.executeSQL("Select * from "+tabela);
            int numColunas=con_Alunos.resultset.getMetaData().getColumnCount();
            jTable1.getColumnModel().getColumn(0).setPreferredWidth(5);
            jTable1.getColumnModel().getColumn(1).setPreferredWidth(50);
            jTable1.getColumnModel().getColumn(2).setPreferredWidth(5);
            DefaultTableModel modelo = (DefaultTableModel)jTable1.getModel();
            modelo.setNumRows(0);
            while(con_Alunos.resultset.next())
            {
                modelo.addRow(new Object[]{con_Alunos.resultset.getString("CodigoUsuario"),con_Alunos.resultset.getString("Nome"),con_Alunos.resultset.getString("Matricula"),con_Alunos.resultset.getString("Turma"),con_Alunos.resultset.getString("Rua"),con_Alunos.resultset.getString("Bairro"),con_Alunos.resultset.getString("Telefone"),con_Alunos.resultset.getString("Celular"),con_Alunos.resultset.getString("Email")});
            }
        }
        catch (Exception e)
        {
            JOptionPane.showMessageDialog(rootPane, e.getMessage(),"Erro",JOptionPane.ERROR_MESSAGE);
        }
     }
      private void pesquisar()//Método para Pesquisar no banco de dados
    {
        try
        {
            String valor=CPPESQUISAR.getText();
            con_Alunos.executeSQL("select * from "+tabela+" where Nome like '"+valor+"%'");
            
        }
        catch (Exception e)
        {
            JOptionPane.showMessageDialog(null,"Não foi possivel localizar os dados");
            CPPESQUISAR.setText("");
        }
    }

   

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

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        CPPESQUISAR = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jTable1.setBorder(javax.swing.BorderFactory.createEtchedBorder(null, new java.awt.Color(0, 0, 0)));
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null, null, null}
            },
            new String [] {
                "Codigo", "Nome ", "Matricula", "Turma", "Rua", "Bairro", "Telefone", "Celular", "Email"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class, java.lang.String.class, java.lang.String.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jTable1.setGridColor(new java.awt.Color(51, 153, 255));
        jScrollPane1.setViewportView(jTable1);

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Icones/pesquisaaluno.jpg"))); // NOI18N

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jButton2.setFont(new java.awt.Font("Verdana", 1, 14));
        jButton2.setText("PESQUISAR");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton2)
                .addGap(51, 51, 51)
                .addComponent(CPPESQUISAR, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(11, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(CPPESQUISAR, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(21, Short.MAX_VALUE))
        );

        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(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(436, 436, 436))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(38, Short.MAX_VALUE))
        );

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

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        // TODO add your handling code here:
        con_Alunos.executeSQL("select * from CadastroUsuario where Nome like'%"+CPPESQUISAR.getText());
        preencher_table();
        
}                                        

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new PesquisaAluno().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JTextField CPPESQUISAR;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration

}

ai toda minha classe..

ViniGodoy

Tem um select ali dentro do método preencher_table().

Ele está sobrescrevendo seu filtro.

Dica… não use o DefaultTableModel e crie classes de negócio para seus dados. O seu código está bastante bagunçado.

Criado 16 de abril de 2011
Ultima resposta 16 de abr. de 2011
Respostas 3
Participantes 2