Popular campo de edição com dados de tabela

Sou iniciante em swing,estou com problema na hora de popular os dados que vem da tabela.

Há momentos que popula certo, e a momentos que não popula certo.

não consigo achar o erro, disponibilizarei abaixo o codigo da tela.

quem puder dar uma olhada nos métodos dataTableMouseClicked, limpacampos,setcampos e getcampos, que são os métodos para manipular os dados.

[code]
package ftec.gui;

import dto.Pais;
import ftec.persist.PaisDAO;
import java.util.List;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

public class PaisGUI extends javax.swing.JInternalFrame {

private PaisDAO paisDAO;
private List<Pais> dados;
private Pais pais ;
private Boolean novo;
private int aux;
private int codigo;

public PaisGUI() {
    super("Cadastro de Países",
            true, //resizable
            true, //closable
            true, //maximizable
            true);//iconifiable
    novo = true;
    initComponents();
    paisDAO = new PaisDAO();
    this.dados = paisDAO.getFull();
    
    if ((dados != null) && (!dados.isEmpty())) {
        this.preencheTabela();
    }
    this.statusCampos(false);
    this.setVisible(true);
    limpaCampos();
}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jToolBar1 = new javax.swing.JToolBar();
    btnNew = new javax.swing.JButton();
    jSeparator1 = new javax.swing.JToolBar.Separator();
    btnUpdate = new javax.swing.JButton();
    jSeparator2 = new javax.swing.JToolBar.Separator();
    jSeparator5 = new javax.swing.JToolBar.Separator();
    btnSave = new javax.swing.JButton();
    jSeparator3 = new javax.swing.JToolBar.Separator();
    btnCancel = new javax.swing.JButton();
    jSeparator4 = new javax.swing.JToolBar.Separator();
    jSeparator6 = new javax.swing.JToolBar.Separator();
    btnRemove = new javax.swing.JButton();
    jPedicao = new javax.swing.JPanel();
    jLabel3 = new javax.swing.JLabel();
    tfDescricao = new javax.swing.JTextField();
    jScrollPane1 = new javax.swing.JScrollPane();
    dataTable = new javax.swing.JTable();
    jPanel3 = new javax.swing.JPanel();
    jLabel2 = new javax.swing.JLabel();

    jToolBar1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
    jToolBar1.setRollover(true);

    btnNew.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/new.png"))); // NOI18N
    btnNew.setToolTipText("Novo");
    btnNew.setFocusable(false);
    btnNew.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    btnNew.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    btnNew.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnNewActionPerformed(evt);
        }
    });
    jToolBar1.add(btnNew);
    jToolBar1.add(jSeparator1);

    btnUpdate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/copy.png"))); // NOI18N
    btnUpdate.setToolTipText("Editar");
    btnUpdate.setFocusable(false);
    btnUpdate.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    btnUpdate.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    btnUpdate.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnUpdateActionPerformed(evt);
        }
    });
    jToolBar1.add(btnUpdate);
    jToolBar1.add(jSeparator2);
    jToolBar1.add(jSeparator5);

    btnSave.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/save.png"))); // NOI18N
    btnSave.setToolTipText("Salvar");
    btnSave.setFocusable(false);
    btnSave.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    btnSave.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    btnSave.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnSaveActionPerformed(evt);
        }
    });
    jToolBar1.add(btnSave);
    jToolBar1.add(jSeparator3);

    btnCancel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/undo.png"))); // NOI18N
    btnCancel.setToolTipText("Cancelar");
    btnCancel.setFocusable(false);
    btnCancel.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    btnCancel.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    btnCancel.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnCancelActionPerformed(evt);
        }
    });
    jToolBar1.add(btnCancel);
    jToolBar1.add(jSeparator4);
    jToolBar1.add(jSeparator6);

    btnRemove.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/delete.gif"))); // NOI18N
    btnRemove.setToolTipText("Remover");
    btnRemove.setFocusable(false);
    btnRemove.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
    btnRemove.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
    btnRemove.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnRemoveActionPerformed(evt);
        }
    });
    jToolBar1.add(btnRemove);

    jPanel1.add(jToolBar1);

    jPedicao.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Edição"));
    jPedicao.addComponentListener(new java.awt.event.ComponentAdapter() {
        public void componentHidden(java.awt.event.ComponentEvent evt) {
            jPedicaoComponentHidden(evt);
        }
    });

    jLabel3.setText("Descrição");

    javax.swing.GroupLayout jPedicaoLayout = new javax.swing.GroupLayout(jPedicao);
    jPedicao.setLayout(jPedicaoLayout);
    jPedicaoLayout.setHorizontalGroup(
        jPedicaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPedicaoLayout.createSequentialGroup()
            .addGap(127, 127, 127)
            .addComponent(jLabel3)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(tfDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, 296, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(142, Short.MAX_VALUE))
    );
    jPedicaoLayout.setVerticalGroup(
        jPedicaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPedicaoLayout.createSequentialGroup()
            .addGroup(jPedicaoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel3)
                .addComponent(tfDescricao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addContainerGap(22, Short.MAX_VALUE))
    );

    jScrollPane1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Dados"))));

    dataTable.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {

        },
        new String [] {
            "", "Código", "Descricao"
        }
    ) {
        Class[] types = new Class [] {
            java.lang.Boolean.class, java.lang.Integer.class, java.lang.String.class
        };
        boolean[] canEdit = new boolean [] {
            true, false, false
        };

        public Class getColumnClass(int columnIndex) {
            return types [columnIndex];
        }

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit [columnIndex];
        }
    });
    dataTable.setColumnSelectionAllowed(true);
    dataTable.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
    dataTable.addMouseListener(new java.awt.event.MouseAdapter() {
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            dataTableMouseClicked(evt);
        }
    });
    jScrollPane1.setViewportView(dataTable);
    dataTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    dataTable.getColumnModel().getColumn(0).setMaxWidth(20);
    dataTable.getColumnModel().getColumn(1).setMaxWidth(50);

    jPanel3.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

    jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 24));
    jLabel2.setText("Cadastro de Países");
    jPanel3.add(jLabel2);

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, 627, Short.MAX_VALUE)
        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 627, Short.MAX_VALUE)
        .addComponent(jPedicao, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 627, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 47, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jPedicao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>//GEN-END:initComponents

private void btnNewActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewActionPerformed
    limpaCampos();
    this.statusCampos(true);
}//GEN-LAST:event_btnNewActionPerformed

private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateActionPerformed
    setCampos(pais);
    this.statusCampos(true);
    novo = false;
}//GEN-LAST:event_btnUpdateActionPerformed

private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
    this.statusCampos(false);
    limpaCampos();
}//GEN-LAST:event_btnCancelActionPerformed

private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
    getCampos();
    pais.setCodigo(codigo);
    if (pais.getNome().isEmpty()) {
        JOptionPane.showMessageDialog(null, "Nome do País não informado");
    } else {
        if (novo) {
            paisDAO.insert(pais);
            JOptionPane.showMessageDialog(null, "País inserido com sucesso!");
        } else {
            paisDAO.update(pais);
            JOptionPane.showMessageDialog(null, "País alterado com sucesso!");
        }
        novo = true;
        dados = paisDAO.getFull();

        if (dados != null) {
            preencheTabela();
        }
        this.statusCampos(false);
        limpaCampos();
    }
}//GEN-LAST:event_btnSaveActionPerformed

private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveActionPerformed
    setCampos(pais);
    int conf = JOptionPane.showConfirmDialog(null, "Confirma a Exclusao?", "Confirmacao", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
    if (conf != 0) {
        return;
    }
    paisDAO.remove(pais);
    dados.remove(pais);
    if (dados != null) {
        preencheTabela();
    }
    limpaCampos();
}//GEN-LAST:event_btnRemoveActionPerformed

private void dataTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_dataTableMouseClicked
    int row = dataTable.getSelectedRow();
    dataTable.clearSelection();
    if (row >= 0) {
        DefaultTableModel model = (DefaultTableModel) dataTable.getModel();
        boolean sel = (Boolean) model.getValueAt(row, 0);
      if (sel) {
            aux = row;
            Integer cod = (Integer) model.getValueAt(row, 1);
           
            for (Pais p : dados) {
                if (p.getCodigo() == cod) {
                    pais = p;
                    codigo = p.getCodigo();
                    break;
                }
            }
       }
    }
}//GEN-LAST:event_dataTableMouseClicked
private void jPedicaoComponentHidden(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_jPedicaoComponentHidden
}//GEN-LAST:event_jPedicaoComponentHidden
private void limpaCampos() {
    this.tfDescricao.setText("");
    DefaultTableModel model = (DefaultTableModel) dataTable.getModel();
    model.setValueAt(false, aux, 0);
}

private void setCampos(Pais pais) {
            this.tfDescricao.setText(pais.getNome());
}

private void getCampos() {
    pais.setNome(this.tfDescricao.getText());
}

private void statusCampos(boolean status) {
    this.btnNew.setEnabled(!status);
    this.btnUpdate.setEnabled(!status);
    this.btnSave.setEnabled(status);
    this.btnCancel.setEnabled(status);
    this.btnRemove.setEnabled(!status);
    this.tfDescricao.setEnabled(status);
    this.jPedicao.setVisible(status);
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCancel;
private javax.swing.JButton btnNew;
private javax.swing.JButton btnRemove;
private javax.swing.JButton btnSave;
private javax.swing.JButton btnUpdate;
private javax.swing.JTable dataTable;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPedicao;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JToolBar.Separator jSeparator1;
private javax.swing.JToolBar.Separator jSeparator2;
private javax.swing.JToolBar.Separator jSeparator3;
private javax.swing.JToolBar.Separator jSeparator4;
private javax.swing.JToolBar.Separator jSeparator5;
private javax.swing.JToolBar.Separator jSeparator6;
private javax.swing.JToolBar jToolBar1;
private javax.swing.JTextField tfDescricao;
// End of variables declaration//GEN-END:variables

public void preencheTabela() {
    DefaultTableModel model = (DefaultTableModel) this.dataTable.getModel();
    while (dataTable.getRowCount() > 0) {
        model.removeRow(0);
    }
    for (Pais p : dados) {
        model.addRow(new Object[]{new Boolean(false), p.getCodigo(), p.getNome()});
    }
}

}[/code]

É um projeto de aula, já mostrei pra meu professor e ele não encontrou defeito no código, meu projeto já tem umas 50 telas, e todas tem o mesmo padrão para popupal os dados.

Já fiz varios testes, e perd bastante tempo para descobrir onde esta o defeito.

Agradeço quem puder olhar o código.

fiquem com total liberdade para apontar defeitos, o importante para mim é aprender e não entregar o trabalho.

Valeu

nada! :frowning:

Você pode começar não usando o DefaultTableModel. Veja os links da minha assinatura.

ViniGodoy estou tentando criar minha tabela a a partir do modelo que tu fez de livros.
Mas ainda não estou entendendo… to ficando louco!

Poste então o modelo que você fez aí, baseado no meu, e que não funciona.

public void setValueAt(Object aValue, int rowIndex, int columnIndex) { //Vamos alterar o valor da coluna columnIndex na linha rowIndex com o valor aValue passado no parâmetro. //Note que vc poderia alterar 2 campos ao invés de um só. if (columnIndex== COL_TITULO) titulo.setTitulo(aValue.toString()); else if (columnIndex== COL_AUTOR) titulo.getAutor().setNome(aValue.toString()); }

tipo do teu exemplo este titulo vem da onde, se não tem variavel local nem da classe?

no meu exemplo eu tenho um tabela que tem coluna pra marcar uma pra codigo e outra pra nome.
quando marcar a primeira coluna e clicar no botão editar, abre um panel de edição, com um objeto Pais setado conforme os dados da linha da tabela selecionada.

Veja como fiz

[code]import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;

public class Tabela extends AbstractTableModel {
private static final int COL_COD = 1;
private static final int COL_NOME = 2;
private static final int COL_SEL = 0;
private List valores;

//Esse é um construtor, que recebe a nossa lista de paises
public Tabela(List<Pais> valores) {  
      this.valores = new ArrayList<Pais>(valores);  
}  

public int getRowCount() {  
    //Quantas linhas tem sua tabela? Uma para cada item da lista.  
    return valores.size();  
}  

public int getColumnCount() {  
    //Quantas colunas tem a tabela? Nesse exemplo, só 2.  
    return 3;  
}  

public String getColumnName(int column) {  
    //Qual é o nome das nossas colunas?  
	if (column == COL_SEL) return ""; // não quero nome 
    if (column == COL_COD) return "Código";  
    if (column == COL_NOME) return "Nome";  
    return ""; //Nunca deve ocorrer  
}  

public Object getValueAt(int row, int column) {  
    //Precisamos retornar o valor da coluna column e da linha row.  
    Pais pais = valores.get(row);  
    if (column == COL_COD) return pais.getCodigo();  
    else if (column == COL_NOME) return pais.getNome();
    else if(column == COL_SEL) return false;
    return ""; //Nunca deve ocorrer  
}  

public void setValueAt(boolean sel, int rowIndex,int column) {  
	
	
	//quero modificar os dois como coloco?
    
}  

public Class<?> getColumnClass(int columnIndex) {  
    //Qual a classe das nossas colunas? Como estamos exibindo texto, é string.  
    if(columnIndex==2)return String.class;
    else return int.class;
    
    
}  
  
public boolean isCellEditable(int rowIndex, int columnIndex) {  
   if(columnIndex == 0) 
    return true;  
   else return false;
}  
//Já que esse tableModel é de livros, vamos fazer um get que retorne um livro inteiro.  
//Isso elimina a necessidade de chamar o getValueAt() nas telas.   
public Pais get(int row) {  
    return valores.get(row);  
}  

}[/code]

veja como coloquei, estou um pouco confuso, na construção como coloco
pra ele colocar um marcador na primeira coluna? ,e o setValue, como coloco ja que tenho informações de um pais e mais um boleano?

Mas vc quer que a edição seja na tabela, ou só na sua tela?

E por que ao invés de ter uma coluna sel, vc não usa a própria linha de seleção do JTable?

Mas vc quer que a edição seja na tabela, ou só na sua tela?
hoje faço nos dois, está errado?

E por que ao invés de ter uma coluna sel, vc não usa a própria linha de seleção do JTable?
não entendi direito tua pergunta, abaixo tentei explicar como estou fazendo.

meu projeto está assim:
as telas de cadastro estão seguindo o mesmo layout.
tem uma barra de botoes, um painel de edição e uma tabela com os dados cadastrados.
quando seleciona uma linha da tabela:
a função dataTableMouseClicked está populando meu objeto.
qdo clico no botão alterar eu habilito meu painel de edição e seto os campos de texto
com meu objeto populado pelo(dataTableMouseClicked).

se eu clicar no botão cancelar, meu panel edição é desabilitado, e o campo da tabela que

estava selecionado é deselecionado.

se eu clico em salvar ai altero no banco, removo os dados da tabela e populo a tabela

novamente com preencheTabela()

quando eu clico em novo acontece a mesma coisa que quando altero, apenas um boleano faz um

controle, se é novo ou alteração. Mas a tabela quando é modificada, eu sempre uso o preenche

tabela.

estava usando o defaultTabelmodel, queria apenas mudar o model, conforme voces aconcelharam,
mas não queria mudar o layout da tela.

Acho que como está a tela não posso tirar meu campo de seleção da tabela(por usabilidade).

eu estou errado em refazer tabela a cada nova inclusão ou alteração de linha?
(faço assim por não ter perigo de ter os dados da tela de um jeito e no banco de outro.)

estou aprendendo pode apontar os defeitos!
valeu