jTable retorna vazio mas insere dados corretamente no TextField

0 respostas
C

Boa tarde amigos do fórum… estou quebrando a cabeça a mais de 1 semana em cima do meu jTable e não consigo descobrir o erro. É o seguinte: eu tenho uma aplicação básica com campos CÓDIGO/SEXO/OBS e utilizo o MySQL. A conexão com o banco está perfeita, eu adiciono e excluo registros sem problemas, mas eu tenho um botão LOCALIZAR onde cada vez que ele é clicado e o form está vazio ele busca tudo o que tem no banco e preenche o jTable. Ai o usuário clica no registro que quer manipular e clica em RESTAURAR, ai a minha tela deveria ficar preenchida. O meu problema é o seguinte: eu consigo por exemplo colocar no campo código = 1, ai se eu clico em LOCALIZAR o form é preenchido mas a tabela aparece VAZIA… já tentei de tudo e não acho o erro… Por favor me ajudem a solucionar o problema… o código da tabela esta abaixo:
Quote:
/*

  • PesquisarAnimal.java
  • Created on 3 de Março de 2009, 10:18
    */
package testejtable;

import java.awt.<em>;

import javax.swing.</em>;

import java.sql.<em>;

import java.util.</em>;

/**
*

  • @author Carlos
    */
    public class PesquisarAnimal extends javax.swing.JFrame {
    private String driver;
    private String url;
    private String userName;
    private String password;
    private Connection conn;
    private String CodAnimal = “”;
/** Creates new form PesquisarAnimal */

public PesquisarAnimal(java.awt.Frame parent, boolean modal) {

//super(parent, modal);

initComponents();

// Recupera arquivo de propriedades

Configuracao cf = new Configuracao();

driver = cf.getDriver();

url = cf.getUrl();

userName = cf.getUserName();

password = cf.getPassword();
try {

Class.forName(driver);

conn = DriverManager.getConnection(url, userName, password);

}

catch (ClassNotFoundException cnfex) {

System.err.println(Não foi possível carregar o driver. );

cnfex.printStackTrace();

System.exit(1); // Encerra o programa

}

catch (SQLException sqlex) {

System.err.println(Não foi possível estabelecer conexão. );

sqlex.printStackTrace();

}

// Recupera dados da tabela

pesquisaTabela();

}

/** This method is called from within the constructor to

  • initialize the form.
  • WARNING: Do NOT modify this code. The content of this method is
  • always regenerated by the Form Editor.
    */
    @SuppressWarnings(“unchecked”)
    //
    private void initComponents() {
pnlSuperior = new javax.swing.JPanel();

btnRecuperar = new javax.swing.JButton();

btnSair = new javax.swing.JButton();

tabela = new javax.swing.JTable();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

btnRecuperar.setText(“Recuperar”);

btnRecuperar.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

btnRecuperarActionPerformed(evt);

}

});

pnlSuperior.add(btnRecuperar);
btnSair.setText(“Sair”);

btnSair.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

btnSairActionPerformed(evt);

}

});

pnlSuperior.add(btnSair);
tabela.setAutoCreateRowSorter(true);

tabela.setModel(new javax.swing.table.DefaultTableModel(

new Object [][] {

{null, null, null, null},

{null, null, null, null},

{null, null, null, null},

{null, null, null, null},

{null, null, null, null}

},

new String [] {

“Title 1”, “Title 2”, “Title 3”, “Título 4”

}

));

tabela.setColumnSelectionAllowed(true);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(pnlSuperior, javax.swing.GroupLayout.DEFAULT_SIZE, 612, Short.MAX_VALUE)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addComponent(tabela, javax.swing.GroupLayout.DEFAULT_SIZE, 612, Short.MAX_VALUE))

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addComponent(pnlSuperior, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

.addContainerGap(400, Short.MAX_VALUE))

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()

.addContainerGap(42, Short.MAX_VALUE)

.addComponent(tabela, javax.swing.GroupLayout.PREFERRED_SIZE, 380, javax.swing.GroupLayout.PREFERRED_SIZE)

.addContainerGap()))

);

tabela.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);

pack();
}//

private void btnRecuperarActionPerformed(java.awt.event.ActionEvent evt) {

pegaValor();

fechaConexao();

setVisible(false);

dispose();

}
private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {

CodAnimal = “”;

fechaConexao();

setVisible(false);

dispose();

}
private void pesquisaTabela() {

Statement comm;

ResultSet resultSet;

try {

String query = " select CodAnimal, SexoAnimal, ObsAnimal "
  • " from ANIMAIS "
  • " order by CodAnimal ";
    comm = conn.createStatement();
    resultSet = comm.executeQuery(query);
    exibeDados(resultSet);
    comm.close();
    }
    catch (SQLException sqlex) {
    sqlex.printStackTrace();
    }
    }
private void exibeDados(ResultSet rs) throws SQLException {

// Posiciona para o primeiro registro

boolean registros = rs.next();

// Verifica se a tabela contém registros

if (!registros) {

JOptionPane.showMessageDialog(this, Tabela vazia! );

setTitle(Sem registros para exibir );

return;

}

setTitle(Matérias);

Vector colunas = new Vector();

Vector linhas = new Vector();

try {

// Monta cabeçalhos das colunas

ResultSetMetaData rsmd = rs.getMetaData();

for (int i = 1; i <= rsmd.getColumnCount(); ++i) {

colunas.addElement(trataNomeColuna(rsmd.getColumnName(i)));

}

do {

linhas.addElement(recuperaDados(rs, rsmd));

} while (rs.next());
// Exibe os dados

tabela = new JTable(linhas, colunas);

JScrollPane scroller = new JScrollPane(tabela);

getContentPane().add(scroller, BorderLayout.CENTER);

validate();

}

catch (SQLException sqlex) {

sqlex.printStackTrace();

}

}
private Vector recuperaDados(ResultSet rs, ResultSetMetaData rsmd)

throws SQLException {

Vector dadosTabela = new Vector();

for (int i = 1; i <= rsmd.getColumnCount(); ++i) {

dadosTabela.addElement(rs.getString(i));

}

return dadosTabela;

}
private void fechaConexao() {

try {

conn.close();

}

catch (SQLException sqlex) {

System.err.println( “Não foi possível encerrar a conexão.” );

sqlex.printStackTrace();

}

}
private void pegaValor() {

int row;

int col = 0;

try {

row = tabela.getSelectedRow();

if (row >= 0) {

Object data = tabela.getValueAt(row, col);

CodAnimal = data.toString();

}

}

catch(Exception e) {

CodAnimal = “”;

}

}

private String trataNomeColuna(String str) {
String result = “”;

String[] nomeColuna = new String[3];

nomeColuna[0] = “CodAnimal”;

nomeColuna[1] = “SexoAnimal”;

nomeColuna[2] = “ObsAnimal”;
String[] nomeTratado = new String[3];

nomeTratado[0] = “Código”;

nomeTratado[1] = “Sexo”;

nomeTratado[2] = “Obs”;
for (int i = 0; i <= nomeColuna.length; ++i) {

if (str.toUpperCase().trim().equals(nomeColuna[i].toUpperCase().trim())) {

result = nomeTratado[i];

break;

}

}

return result;

}
public String getCodAnimal() {

return CodAnimal;

}

/**

  • @param args the command line arguments
    /
    /
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    new PesquisarAnimal().setVisible(true);
    }
    });
    }*/
// Variables declaration - do not modify

private javax.swing.JButton btnRecuperar;

private javax.swing.JButton btnSair;

private javax.swing.JPanel pnlSuperior;

private javax.swing.JTable tabela;

// End of variables declaration

}

:shock:

Criado 3 de março de 2009
Respostas 0
Participantes 1