Tabela não atualiza linhas[RESOLVIDO]

5 respostas
guisantogui

quero fazer uma pesquisa no banco de dados e jogar o retorno em um jTable, eu ja consigo fazer isso com todos os registros da tabela, mas quando pesquiso apenas um usuário (pelo codigo) ele mantem a tabela igual, com todos os registros, mas se eu redimensionar a tela fica apenas os dados do código que eu passei, MUITO ESTRANHO.

Segue meu código.

Evento:

private void btnPesquisaClienteActionPerformed(java.awt.event.ActionEvent evt) {                                                   
        ClienteTableModel ctm = (ClienteTableModel) tabClientes.getModel();

        if(txtCod.getText().isEmpty() && txtNome.getText().isEmpty()){
            ctm.setDados(clienteDao.getClientes());
        }
        else if(!txtCod.getText().isEmpty()){
            List<Cliente> ls = new ArrayList<Cliente>();
            ls.add(clienteDao.getClienteId(Integer.parseInt(txtCod.getText())));
            ctm.setDados(ls);
            tabClientes.setModel(ctm);
        }
    }

metodo de pesquisa no DB:

private final String SELECTID = "SELECT idCliente, nome, endereco, telefone, data_nasc FROM NotaFiscalEletronica.Cliente WHERE idCliente=?;";

public Cliente getClienteId(int id){
    Connection connection = new ConnectionFactory().getConnection();
    StringBuilder sb = new StringBuilder();
        try {
            Calendar cal = Calendar.getInstance();
            Cliente c;
            PreparedStatement prepStm = connection.prepareStatement(SELECTID);
            prepStm.setInt(1, id);
            ResultSet rs = prepStm.executeQuery();
            rs.first();

            cal.setTimeInMillis(rs.getDate("data_nasc").getTime());
            
            c = new Cliente(rs.getInt("idCliente"), rs.getString("nome"), rs.getString("endereco"), rs.getString("telefone"), cal);

            return c;
        }
        catch (SQLException ex) {
            ex.printStackTrace();
            return null;
        }
        finally{
            try {
                connection.close();
            }
            catch (SQLException ex) {
                throw new RuntimeException("Quebra na conexão com o database");
            }
        }
    }

Gente, ta bem estranho isso se alguém souber o que é pls responde :D

5 Respostas

cardosao

Ola, boa noite.

Veja se meu codigo te ajuda. Se tiver duvidas é só chamar.

private void atualizaTabela( String nome ){
  List<Usuario> lista = null;
    if ( nome != null && !nome.equals("") ){
        lista = new UsuarioDao().getByDescricao( nome );
    } else {
        lista = new UsuarioDao().getAll();
    }
    DefaultTableModel model = (DefaultTableModel)jtable.getModel();
    model.setRowCount( lista.size() );
    for ( int i = 0; i < lista.size(); i++ ){
        model.setValueAt( lista.get(i).getId() , i, 0);
        model.setValueAt( lista.get(i).getNome() , i, 1);
        model.setValueAt( lista.get(i).getSetor().getNome() , i, 2);
        model.setValueAt( lista.get(i).getEmail() , i, 3);
        model.setValueAt( lista.get(i).getNivel() , i, 4);
        model.setValueAt( lista.get(i).getCentroCusto().getNome() , i, 5);
     }
}

[]s

ViniGodoy

No método setDados, você está chamando o método fireTableDataChanged?
Outra coisa… não é necessário chamar o setModel. Quando vc chamar o setDados, a tabela irá se atualizar automaticamente.

Não utilize DefaultTableModel. Seu código fica muito mais lento, ocupa mais memória, fica mais difícil de manter, menos seguro e menos modularizado.
Veja como seria o mesmo código sem o default:

private void atualizaTabela( String nome ){ List<Usuario> lista = null; if ( nome != null && !nome.trim().isEmpty() ){ lista = new UsuarioDao().getByDescricao( nome ); } else { lista = new UsuarioDao().getAll(); } UsuarioTableModel model = (UsuarioTableModel)jtable.getModel(); model.setDados(lista); } }

guisantogui
ViniGodoy:
No método setDados, você está chamando o método fireTableDataChanged? Outra coisa... não é necessário chamar o setModel. Quando vc chamar o setDados, a tabela irá se atualizar automaticamente.

BOA VINI, muito boa!!
Não tava chamando essa porcaria do fireTableDataChanged!
Vlw pela ajuda!
E aliás, DTM never more. Segue o meu tableModel:

public class ClienteTableModel extends AbstractTableModel{

    private ClienteDAO cdao = new ClienteDAO();
    public static final String[] COLUNAS = {"ID","Nome","Endereco","Telefone","Data de nascimento"};
    private List<Cliente> dados;

    public ClienteTableModel(){
        dados = cdao.getClientes();
    }

    public ClienteTableModel(List<Cliente> clientes){
        dados = clientes;
    }

    public void addRow(Cliente c){
        dados.add(c);
        fireTableRowsInserted(dados.size()-1, dados.size()-1);
    }

    public void removeRow(Cliente c){
        fireTableRowsDeleted(dados.indexOf(c), dados.indexOf(c));
        dados.remove(c);
    }

    public void removeRow(int i){
        fireTableRowsDeleted(i, i);
        dados.remove(i);
    }

    public int getRowCount() {
        return dados.size();
    }

    @Override
    public Class<?> getColumnClass(int columnIndex){
        if(columnIndex == 3){
            return Calendar.class;
        }
        else{
            return String.class;
        }
    }

    public int getColumnCount() {
        return COLUNAS.length;
    }

    public Object getValueAt(int rowIndex, int columnIndex) {
        Cliente cliente = dados.get(rowIndex);
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        switch(columnIndex){
            case 0: return cliente.getId();
            case 1: return cliente.getNome();
            case 2: return cliente.getEndereco();
            case 3: return cliente.getTelefone();
            case 4: return sdf.format(new Date (cliente.getData().getTimeInMillis()));
            default: throw new IndexOutOfBoundsException("Opção não encontrada");
        }
    }

    public Cliente getPessoa(int row){
        if(row < dados.size()){
            return dados.get(row);
        }
        else{
            throw new IndexOutOfBoundsException("Numero maior que o tamanho da lista");
        }
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex){
        return false;
    }

    @Override
    public String getColumnName(int column){
        return COLUNAS[column];
    }

    public void setDados(List<Cliente> ls){
        dados = ls;
        fireTableDataChanged();
    }
}
ViniGodoy

Esses métodos “fire” são usados para avisar o JTable que o model mudou. A Table não tem como saber disso a menos que o model dispare (fires) um evento.

guisantogui

Boa Vini, o guj sempre me salvando!

Criado 26 de março de 2011
Ultima resposta 27 de mar. de 2011
Respostas 5
Participantes 3