Como emplementar o tableModel Num Jframe

5 respostas
Nelsonjahn

Olá alguem tem como dar um exemplo de como implantar o table model do exemplo do Towel, num Frame ou jframe.
Não estou entendendo de como fazer isso. agradeço com exemplos. Obrigado.

5 Respostas

ViniGodoy
Nelsonjahn

Olá Vini, Obrigado pela dica mas eu ja olhei varias vezes pois estou no netbeans e colocando a tabela direto é facil pois nao entendo de como impementar ele, até ja entendi mais ou menos o tablemodel do Towel pois fiz funcionar e com a tabela somente funcionou, mas meu problema é entender de como implementar ele no Jframe como abaixo.

package cadastros;

import devsv.tablemodel.Socio;
import javax.swing.table.TableModel;
import utilitarios.jTable;
import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.List; 
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import devsv.tablemodel.SocioTableModel;

public class TesteTabela extends javax.swing.JFrame {
   
  
    public TesteTabela() {
        initComponents();
        
        setTitle("Teste no Jframe");
        setLocation(12, 30);
        setSize(1000, 700);
        
        
    }
  
    @SuppressWarnings("unchecked")
   
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 932, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 492, Short.MAX_VALUE)
        );

        pack();
    }
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TesteTabela().setVisible(true);
            }
        });
    }

   

}
ViniGodoy

Ué, basta criar o model e associar ao seu JTable.

List<Socio> socios = new SocioDao().carregar(); tblSocio.setModel(new SocioTableModel(socios));

Se for usar com o ObjectTableModel, fica igual:

List<Socio> socios = new SocioDao().carregar(); tblSocio.setModel(new ObjectTableModel(socios));

Mas para isso você tem que ter o objeto socio com as devidas anotações.

Nelsonjahn

Essa é a classe Socio

public class Socio {
    
    private String codigo;
    private String descricao; 
    private String uf;

    
    public String  getCodigo() {
        return codigo;
    }
    public String  getDescricao() {
        return descricao;
    }
   public String  getUf() {
        return uf;
    }
   public void setCodigo(String codigo){
       this.codigo=codigo;
   }
   public void setDescricao(String descricao){ 
       this.descricao=descricao;
   }
   public void setUf(String uf){
       this.uf=uf;
   } 

}

A Classe SocioTable Model Abaixo!

import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
 
public class SocioTableModel extends AbstractTableModel{
  
    private List<Socio> linhas;
 
    public SocioTableModel() {
        linhas = new ArrayList<Socio>();
    } 
    public SocioTableModel(List<Socio> listaDeSocios) {
        linhas = new ArrayList<Socio>(listaDeSocios);
    }
   
    private String[] colunas = new String[] {"CÓDIGO","DESCRIÇÃO","UF"};
   
    private static final int CODIGO = 0;
    private static final int DESCRICAO = 1;
    private static final int UF = 2;
    
    @Override
 public int getRowCount() {
    return linhas.size();
}
    @Override
public int getColumnCount() {
    return colunas.length;
}
    @Override
public String getColumnName(int columnIndex) {
    return colunas[columnIndex];
};
    @Override
public Class<?> getColumnClass(int columnIndex) { 
    switch (columnIndex) {
    case CODIGO:
        return String.class;
    case DESCRICAO:
        return String.class;
        case UF:
        return String.class;
    default:      
        throw new IndexOutOfBoundsException("columnIndex out of bounds");
    }
}
    @Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
    return false;
}
    @Override
public Object getValueAt(int rowIndex, int columnIndex) {
    Socio socio = linhas.get(rowIndex);
 
    switch (columnIndex) {
    case CODIGO:
        return socio.getCodigo();
    case DESCRICAO:
        return socio.getDescricao();
        case UF:
        return socio.getUf();
    default:
        throw new IndexOutOfBoundsException("columnIndex out of bounds");
    }
}
    @Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
     Socio socio = linhas.get(rowIndex);
 
    switch (columnIndex) {
    case CODIGO:
        socio.setCodigo((String) aValue);
        break;
    case DESCRICAO:
        socio.setDescricao((String) aValue);
        break;
        case UF:
        socio.setUf((String) aValue);
        break;
    default:
        throw new IndexOutOfBoundsException("columnIndex out of bounds");
    }
     
    fireTableCellUpdated(rowIndex, columnIndex); // Notifica a atualização da célula
}
   
public Socio getSocio(int indiceLinha) {
    return linhas.get(indiceLinha);
}
 

public void addSocio(Socio socio) {
     linhas.add(socio);
     int ultimoIndice = getRowCount() - 1;
 
   
    fireTableRowsInserted(ultimoIndice, ultimoIndice);
}
public void removeSocio(int indiceLinha) {
   
    linhas.remove(indiceLinha);
 
    
    fireTableRowsDeleted(indiceLinha, indiceLinha);
}
public void addListaDeSocios(List<Socio> socios) {
    int indice = getRowCount();
    
    linhas.addAll(socios);
 
    fireTableRowsInserted(indice, indice + socios.size());
}
 
public void limpar() {
    linhas.clear();
 
    fireTableDataChanged();
}
}

e essa é a tabela funcionando pr si sem o jframe,
Não estou entendendo de como coloco ela dentro do frame
Desculpe a ignorancia mas ainda sou muito novo em java, pois sempre fazia com DefaultTableModel.

import java.awt.EventQueue;
import java.util.ArrayList;
import java.util.List; 
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
 
public class SocioTablelModeTest extends JFrame {
    private JTable tblSocios;
    private SocioTableModel tableModel;

    public SocioTablelModeTest() {
       super("Titulo");
        initialize();           
                
    }
 
   private void initialize() {
    setSize(400, 150);
    setLocation(300, 300);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    getContentPane().add(new JScrollPane(getTblSocios()));
}
 
    private JTable getTblSocios() {
        if (tblSocios == null) {
            tblSocios = new JTable();
            tblSocios.setModel(getTableModel());
        }
        return tblSocios;
    }
 
    private SocioTableModel getTableModel() {
        if (tableModel == null) {
            tableModel = new SocioTableModel(criaSocios());
        }
        return tableModel;
    }
    private List<Socio> criaSocios() {
        List<Socio> socios = new ArrayList<Socio>();
        for (int i = 0; i <= 0; i++) {
          Socio socio = new Socio();
            //socio.setNome("Nome" + i);
            //socio.setEndereco("Endereço" + i);
            socios.add(socio);
       }
        return socios;
    }
    @SuppressWarnings("unchecked")
                   
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        pack();
    }   
  
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new SocioTablelModeTest().setVisible(true);
            }
        });
    }
 
}
Nelsonjahn

Pessoal se alguem se habilitar em me dar um pequeno exemplo ajudaria muito pois sou iniciante em java e gostaria de implantar o table model porém nao sei como fazer implementar no meu jframe, se prescisar eu posto o código da minha aplicação atual com o defaultTablemodel. desde ja agradeço.

Criado 3 de março de 2013
Ultima resposta 6 de mar. de 2013
Respostas 5
Participantes 2