Olá amigos estou iniciando com o AbstractTableModel e vi que temos o Projeto Towel, não vi aqui no fórum um tópico com exemplares de uso do mesmo se alguém tem e poder me ajudar fico grato…
Você já segui o tutorial?
Qualquer duvida é só postar.
Sim estou estudando sobre ele minha dúvida é como deixar o Texto dos filtro da TableFilter em pt-br, e como salvar, editar, ou excluir registros diretamente da TableModel, estou usando o TableFilter mas quando eu filtro e salvo o filtro em um objeto e quero ver um atribo como Id ele mostra o da tablemodel e não o do registro, exemplo uma entidade de Uf eu listo todas as uf e filtro com a Sigla MT ai quero ver o id da mesma ele me retorna 1
Meu Model
package model;
import com.towel.el.annotation.Resolvable;
public class Uf {
@Resolvable(colName=" Codigo ")
private int id;
@Resolvable(colName=" Codigo Ibge ")
private String codigo;
@Resolvable(colName=" Sigla ")
private String sigla;
@Resolvable(colName="Nome da uf")
private String nome;
@Resolvable(colName=" Ativo ")
private Boolean ativo;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCodigo() {
return codigo;
}
public void setCodigo(String codigo) {
this.codigo = codigo;
}
public String getSigla() {
return sigla;
}
public void setSigla(String sigla) {
this.sigla = sigla;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Boolean getAtivo() {
return ativo;
}
public void setAtivo(Boolean ativo) {
this.ativo = ativo;
}
}
meu dao so com o metodo listar
[code]package dao;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import model.Uf;
public class UfDao extends ConexaoMySQL{
public List<Uf> listarTodas(String descricao)throws Exception{
List<Uf> ufs = new ArrayList<Uf>();
String sql = "Select * from Uf";
pstm = getPreparedStatement(sql);
rs = pstm.executeQuery();
while(rs.next()){
Uf uf = null;
uf = populaUf(rs);
ufs.add(uf);
}
return ufs;
}
public Uf populaUf(ResultSet rs)throws Exception{
Uf uf = new Uf();
uf.setId(rs.getInt(1));
uf.setCodigo(rs.getString(2));
uf.setSigla(rs.getString(3));
uf.setNome(rs.getString(4));
uf.setAtivo(rs.getBoolean(5));
return uf;
}
}
[/code]
meu view
package view;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.border.EtchedBorder;
import javax.swing.table.TableColumnModel;
import model.Uf;
import com.towel.el.annotation.AnnotationResolver;
import com.towel.swing.table.ObjectTableModel;
import com.towel.swing.table.Resizer;
import com.towel.swing.table.TableFilter;
import dao.UfDao;
public class Tabela extends JDialog {
final JButton botao = new JButton("X");
private final JPanel panelTable = new JPanel();
/**
* u Launch the application.
*/
public static void main(String[] args) {
try {
mudar_layout_visual_os();
Tabela dialog = new Tabela();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setLocationRelativeTo(null);
dialog.setTitle("Exemplo JTable com o projeto Towel");
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public Tabela() {
setBounds(100, 100, 577, 305);
getContentPane().setLayout(new BorderLayout());
panelTable.setBorder(new EtchedBorder(EtchedBorder.LOWERED,
Color.BLACK, Color.BLACK));
getContentPane().add(panelTable, BorderLayout.CENTER);
panelTable.setLayout(new GridLayout(1, 0, 0, 0));
{
JPanel buttonPane = new JPanel();
buttonPane.setBorder(new EtchedBorder(EtchedBorder.LOWERED,
Color.BLACK, Color.BLACK));
buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
getContentPane().add(buttonPane, BorderLayout.SOUTH);
{
JButton okButton = new JButton("OK");
okButton.setActionCommand("OK");
buttonPane.add(okButton);
getRootPane().setDefaultButton(okButton);
}
{
JButton cancelButton = new JButton("Cancel");
cancelButton.setActionCommand("Cancel");
buttonPane.add(cancelButton);
}
{
AnnotationResolver resolver = new AnnotationResolver(Uf.class);
final ObjectTableModel<Uf> tableModel = new ObjectTableModel<Uf>(
resolver, "id,codigo,nome,sigla,ativo");
tableModel.isCellEditable(1, 1);
tableModel.setData(getDados());
final JTable table = new JTable();
table.setAutoResizeMode(table.AUTO_RESIZE_OFF);
Resizer expandir = new Resizer();
expandir.fitAllColumns(table);
TableFilter filtro = new TableFilter(table.getTableHeader(),
tableModel);
table.setModel(filtro);
table.getColumnModel().getColumn(0).setPreferredWidth(50);
table.getColumnModel().getColumn(1).setPreferredWidth(100);
table.getColumnModel().getColumn(2).setPreferredWidth(200);
table.getColumnModel().getColumn(3).setPreferredWidth(100);
table.getColumnModel().getColumn(4).setPreferredWidth(100);
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() == 2) {
Uf uf = new Uf();
int row = table.getSelectedRow();
int col = 1;
uf = tableModel.getValue(row);
JOptionPane.showMessageDialog(null,
"Primare Key : " + uf.getId());
}
}
});
JScrollPane pane = new JScrollPane();
pane.setViewportView(table);
panelTable.add(pane);
}
}
}
// Just for create a default List to show.
private List<Uf> getDados() {
UfDao dao = new UfDao();
List<Uf> list = new ArrayList<Uf>();
try {
list = dao.listarTodas("");
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return list;
}
public static void mudar_layout_visual_os() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
}
}
retorno o id do objeto errado
mudar o texto para pt-br
Ok amigos pegar o id correto do objeto foi feito agora é como trabalhar os métodos insert, update, e delete diretamente na ObjectTableModel e como deixar em Pt-br os filtros.
solução do problema de Id do Objeto usando o TableFilter
//É a linha na view, não no model, pois pode estar filtrado
int vwSelected = table.getSelectedRow();
//Obtém o índice dessa linha no model
int mdlSelected = filtro.getModelRow(vwSelected);
//Instancia do obj
Uf uf = tableModel.getValue(mdlSelected);
//Msg informando o id
JOptionPane.showMessageDialog(null,"Primare Key : " + uf.getId());
É isso ai, precisa converter o index pelo table filter.
Sobre insert, crie um botao ou uma ação que crie um objeto vazio e adicioneo dentro do tablemodel, vai ficar uma linha em branco que pode ser preenchida, os valores serão modificados se a tabela for editavel.
Agora salvar eh uma boa pergunta, talvez outro botao.
Certo isso ok, e a questão da descrição do filtro como em ordem crescentes, decrescente e ect… como deixo ele em Pt-br ?
alguém sabe amigos como faço isso ? devo traduzir como ?
Estou com dificuldade na hora de setar o tableModel no jtable:
tableModel.setData(getData());
JTable table = new JTable(tableModel); //ver aqui
Erro:
debug:
java.lang.NoSuchFieldException
at com.towel.reflec.ClassIntrospector.getField(ClassIntrospector.java:96)
at com.towel.reflec.ClassIntrospector.getField(ClassIntrospector.java:102)
at com.towel.reflec.ClassIntrospector.getField(ClassIntrospector.java:79)
at com.towel.el.annotation.AnnotationResolver.resolve(AnnotationResolver.java:57)
at com.towel.el.annotation.AnnotationResolver.resolve(AnnotationResolver.java:80)
at com.towel.swing.table.ObjectTableModel.<init>(ObjectTableModel.java:36)
at FrmSincronizaNovos.montaGridNovos(FrmSincronizaNovos.java:480)
at FrmSincronizaNovos.btnSincronizarActionPerformed(FrmSincronizaNovos.java:302)
at FrmSincronizaNovos.access$100(FrmSincronizaNovos.java:32)
at FrmSincronizaNovos$4.actionPerformed(FrmSincronizaNovos.java:248)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2713)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:707)
at java.awt.EventQueue.access$000(EventQueue.java:101)
at java.awt.EventQueue$3.run(EventQueue.java:666)
at java.awt.EventQueue$3.run(EventQueue.java:664)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:680)
at java.awt.EventQueue$4.run(EventQueue.java:678)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:677)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)