Pessoal tenho uma aplicação, uma JFrame com Jtable e criei um a thread para observar um diretório onde capturo os arquivos, leio e envio dos dados para um banco de dados sqlite. Estou salvando os dados normalmente no sqlite. Como adiciono uma linha da tabela do JTable quando adiciono um registro no banco de dados? tenho que usar Socket ? a aplicação é local. Segue JFrame :
`package form;
import entity.Registro;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import persistencia.RegistroDAO;
import table.RegistroTableModel;
import threads.ArquivoThread;
/**
-
Janela principal
-
@author paulo
-
@version 0.1
*/
public class PrincipalFrame extends javax.swing.JFrame {RegistroTableModel tableModel = new RegistroTableModel();
public PrincipalFrame() {
initComponents();
tableModel.addTableModelListener(lista);
tableModel.addListaDeRegistros(getRegistros());
// getTableModel();}
private RegistroTableModel getTableModel() {
tableModel.addListaDeRegistros(getRegistros());
return tableModel;
}/**
-
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() {jPanel1 = new javax.swing.JPanel();
diretorioDoResultado = new javax.swing.JLabel();
btnIniciar = new javax.swing.JButton();
diretorio = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
lista = new javax.swing.JTable();setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle(“Control - Control-lab Controle de Qualidade de Laboratorios”);
setAlwaysOnTop(true);diretorioDoResultado.setText(“Informe o diretorio dos resultados”);
btnIniciar.setText(“Iniciar”);
btnIniciar.setToolTipText("Clique para iniciar ");
btnIniciar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnIniciarActionPerformed(evt);
}
});lista.setModel(tableModel);
lista.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
jScrollPane1.setViewportView(lista);javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(diretorioDoResultado, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 587, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(diretorio, javax.swing.GroupLayout.PREFERRED_SIZE, 885, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnIniciar, javax.swing.GroupLayout.DEFAULT_SIZE, 67, Short.MAX_VALUE)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(diretorioDoResultado)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(diretorio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnIniciar))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 525, Short.MAX_VALUE))
);javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);pack();
}//
private void btnIniciarActionPerformed(java.awt.event.ActionEvent evt) {
diretorio.setEditable(false);
Thread arquivoTh = new Thread(new ArquivoThread());
arquivoTh.start();}
/**
-
@param args the command line arguments
/
public static void main(String args[]) {
/ Set the Nimbus look and feel /
//
/ If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.- For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if (“Nimbus”.equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(PrincipalFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(PrincipalFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(PrincipalFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(PrincipalFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new PrincipalFrame().setVisible(true);
}
});
} - For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
private ArrayList getRegistros() {
RegistroDAO registroDAO;
ArrayList registros = new ArrayList<>();
try {
registroDAO = new RegistroDAO();
try {
registroDAO.conectar();
registros = (ArrayList) registroDAO.listarTodos();
registroDAO.fecharConexao();
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(PrincipalFrame.class.getName()).log(Level.SEVERE, null, ex);
}} catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(PrincipalFrame.class.getName()).log(Level.SEVERE, null, ex); } return registros;
}
public void addRegistro(Registro registro) {
linhas.add(registro);
fireTableDataChanged();
try {
RegistroDAO registroDAO = new RegistroDAO();
registroDAO.conectar();
registroDAO.adicionar(registro);
registroDAO.fecharConexao();} catch (ClassNotFoundException | SQLException ex) { Logger.getLogger(ArquivoMatrixObserver.class.getName()).log(Level.SEVERE, null, ex); } // Pega a quantidade de registros e subtrai 1 para // achar o último índice. A subtração é necessária // porque os índices começam em zero. int ultimoIndice = getRowCount() - 1; // Notifica a mudança.
}
// Variables declaration - do not modify
private javax.swing.JButton btnIniciar;
private javax.swing.JTextField diretorio;
private javax.swing.JLabel diretorioDoResultado;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable lista;
// End of variables declaration
}
e o observador:
` package observers; -
import entity.Registro;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Scanner;
import table.RegistroTableModel;
public class ArquivoTxtObserver extends ArquivoObserver {
protected Evento evento;
public ArquivoTxtOberver(Evento evento) {
this.evento = evento;
this.evento.attach(this);
}
RegistroTableModel registroModel = new RegistroTableModel();
collection.stream().forEach((r)->{
registroModel.addRegistro(r);
});
// try {
// RegistroDAO registroDAO = new RegistroDAO();
// registroDAO.conectar();
// collection.stream().forEach(® -> {
//
// registroDAO.adicionar®;
//
// });
// registroDAO.fecharConexao();
// (new PrincipalFrame()).atualizarTabela();
// } catch (ClassNotFoundException | SQLException ex) {
// Logger.getLogger(ArquivoMatrixObserver.class.getName()).log(Level.SEVERE, null, ex);
// }
}
}
}
}