[RESOLVIDO] Jtable mostra apenas uma linha

4 respostas
EHS

Galera nunca tinha usao jtable antes e agora estou apanhando um pouco. Faço uma pesquisa no banco e me retorna uma lista de objetos tudo certo, mas na hora que quero exibir na jtable ela mostra apenas o primeiro registro do banco e não sei onde está o problema, pois ainda não entendi direito como funciona o jtable, segue abaixo os códigos.

Lista Animais - tela onde mostra o jtable

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

package filipi;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

/**
 *
 * @author Egon Henrique
 */
public class ListaAnimais extends JFrame {

    private JTable tabela;

    public ListaAnimais() {
        super("Lista de Ovelhas");
        initialize();

        tabela.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if(e.getClickCount() == 2) {
                    int row = tabela.getSelectedRow();
                    String id = String.valueOf(tabela.getValueAt(row, 0));
                    OvelhaGUI ovelhaGUI = new OvelhaGUI();
                    ovelhaGUI.popularDados(id);
                    ovelhaGUI.setVisible(true);
                    setVisible(false);
                }
            }
        });
    }

        private JTable getTblOvelha() {
            if (tabela == null) {
                tabela = new JTable();
                tabela.setModel(new TableModel());
            }

            return tabela;
	}

        private void initialize() {
            setSize(800, 600);
            setDefaultCloseOperation(DISPOSE_ON_CLOSE);
            getContentPane().add(new JScrollPane(getTblOvelha()));
        }
}

Table Model - Modelo da Tabela

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

package filipi;

import filipi.business.OvelhaBusiness;
import filipi.model.Ovelha;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author Egon Henrique
 */
public class TableModel extends AbstractTableModel {

    private String[] colunas = new String[] {
		        "Código", "Brinco", "Sexo", "Repr.", "Vacina", "Dt. Vacina", "Raça"};
    private OvelhaBusiness ovelhaBusiness;
    private Ovelha ovelha;
    private ArrayList<Ovelha> lista;

    public int getRowCount() {
        return 1;
    }

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

    /* Retorna o nome da coluna no índice especificado.
     * Este método é usado pela JTable para saber o texto do cabeçalho. */
    @Override
    public String getColumnName(int columnIndex) {
        // Retorna o conteúdo do Array que possui o nome das colunas
        // no índice especificado.
        return colunas[columnIndex];
    };

    //aqui é onde recebo a lista de objetos do banco e mostra só o primeiro registro
    public Object getValueAt(int rowIndex, int columnIndex) {
       lista = null;
       ovelhaBusiness = new OvelhaBusiness();
       ovelha = null;
        try {
            lista = ovelhaBusiness.getOvelhas();
            for(int i = 0; i < lista.size(); i++) {
                Iterator it = lista.iterator();
                while(it.hasNext()) {
                    ovelha = (Ovelha) it.next();
                    switch (columnIndex) {
                        case 0:
                            return ovelha.getId();
                        case 1:
                            return ovelha.getBrinco();
                        case 2:
                            return ovelha.getSexo();
                        case 3:
                            return ovelha.getReprodutor();
                        case 4:
                            return ovelha.getNomeVacina();
                        case 5:
                            return ovelha.getDataVacina();
                        case 6:
                            return ovelha.getRaca();
                    default:
                            // Se o índice da coluna não for válido, lança um
                            // IndexOutOfBoundsException (Exceção de índice fora dos limites).
                            // Não foi necessário verificar se o índice da linha é inválido,
                            // pois o próprio ArrayList lança a exceção caso seja inválido.
                            throw new IndexOutOfBoundsException("columnIndex out of bounds");
                    }
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(TableModel.class.getName()).log(Level.SEVERE, null, ex);
        }
       return null;
    }

   /*
    permitir alterar conteúdo do Jtable
    @Override
    public boolean isCellEditable(int row, int col) {
        switch (col) {
            case 0:
                return false;
            case 1:
                return true;
            case 2:
                return true;
            case 3: 
                return true;
            case 4:
                return true;
            case 5:
                return true;
            case 6:
                return true;
            default:
                return false;
        }
    }*/

    @Override
    public void setValueAt(Object value, int row, int col) {
   
    }
    
}

4 Respostas

Dani_Gomes

Dá uma olhada na implementação do seu :

Segue o link pra ti dar uma olhada:
http://www.guj.com.br/articles/147

EHS

Vlw pela dica Dani, mas já consegui resolver o problema, estava fazendo a pesquisa no banco na TableModel e não na classe onde mostra a tabela, aqui vai os códigos que funciona.

TableModel

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

package filipi;

import filipi.model.Ovelha;
import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author Egon Henrique
 */
public final class TableModelOvelha extends AbstractTableModel {

    private Ovelha ovelha;
    private ArrayList<Ovelha> linha;
    private String[] colunas;

    public TableModelOvelha(ArrayList<Ovelha> ovelhas, String[] coluna) {
        setLinha(ovelhas);
        setColunas(coluna);
    }

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

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

    /* Retorna o nome da coluna no índice especificado.
     * Este método é usado pela JTable para saber o texto do cabeçalho. */
    @Override
    public String getColumnName(int columnIndex) {
        // Retorna o conteúdo do Array que possui o nome das colunas
        // no índice especificado.
        return colunas[columnIndex];
    };

    public Object getValueAt(int rowIndex, int columnIndex) {
        ovelha = new Ovelha();
        ovelha = linha.get(rowIndex);
        switch (columnIndex) {
            case 0:
                return ovelha.getId();
            case 1:
                return ovelha.getBrinco();
            case 2:
                return ovelha.getSexo();
            case 3:
                return ovelha.getReprodutor();
            case 4:
                return ovelha.getNomeVacina();
            case 5:
                return ovelha.getDataVacina();
            case 6:
                return ovelha.getRaca();
        default:
                // Se o índice da coluna não for válido, lança um
                // IndexOutOfBoundsException (Exceção de índice fora dos limites).
                // Não foi necessário verificar se o índice da linha é inválido,
                // pois o próprio ArrayList lança a exceção caso seja inválido.
                throw new IndexOutOfBoundsException("columnIndex out of bounds");
        }
    }

   public void setLinha(ArrayList<Ovelha> linhas) {
      this.linha = linhas;
   }

   public ArrayList<Ovelha> getLinha() {
      return linha;
   }

   public String[] getColunas() {
      return colunas;
   }

   public void setColunas(String[] colunas) {
      this.colunas = colunas;
   }
   /*
    permitir alterar conteúdo do Jtable
    @Override
    public boolean isCellEditable(int row, int col) {
        switch (col) {
            case 0:
                return false;
            case 1:
                return true;
            case 2:
                return true;
            case 3: 
                return true;
            case 4:
                return true;
            case 5:
                return true;
            case 6:
                return true;
            default:
                return false;
        }
    }*/

    @Override
    public void setValueAt(Object value, int row, int col) {
   
    }
    
}

Lista Animais

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

package filipi;

import filipi.business.OvelhaBusiness;
import filipi.model.Ovelha;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;

/**
 *
 * @author Egon Henrique
 */
public class ListaOvelhas extends JFrame {

    private JTable tabela;
    private OvelhaBusiness ovelhaBusiness;
    private ArrayList<Ovelha> lista;
    private String[] colunas = new String[] {
		        "Código", "Brinco", "Sexo", "Reprodutor", "Vacina", "Dt. Vacina", "Raça"};

    public ListaOvelhas() {
        super("Lista de Ovelhas");
        //this.setLocationRelativeTo(this);
        initialize();

        tabela.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if(e.getClickCount() == 2) {
                    int row = tabela.getSelectedRow();
                    String id = String.valueOf(tabela.getValueAt(row, 0));
                    OvelhaGUI ovelhaGUI = new OvelhaGUI();
                    ovelhaGUI.popularDados(id);
                    ovelhaGUI.setVisible(true);
                    setVisible(false);
                }
            }
        });
    }

    private JTable getTblOvelha() {
        if (tabela == null) {
            tabela = new JTable();
            ovelhaBusiness = new OvelhaBusiness();
            lista = new ArrayList<Ovelha>();
        try {
            lista = ovelhaBusiness.getOvelhas();
        } catch (SQLException ex) {
            Logger.getLogger(ListaOvelhas.class.getName()).log(Level.SEVERE, null, ex);
        }
            tabela.setModel(new TableModelOvelha(lista, colunas));
            tabela.getColumnModel().getColumn(4).setPreferredWidth(400);
            tabela.getColumnModel().getColumn(5).setPreferredWidth(100);
            tabela.getColumnModel().getColumn(6).setPreferredWidth(300);
        }
        return tabela;
    }

    private void initialize() {
        setSize(700, 400);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        getContentPane().add(new JScrollPane(getTblOvelha()));
    }
}
Dani_Gomes

Só não esquece de editar e colocar [Resolvido] no primeiro post do tópico.
Até mais

EHS

É mesmo, tinha esquecido já, vlw.

Criado 29 de novembro de 2011
Ultima resposta 30 de nov. de 2011
Respostas 4
Participantes 2