1
I have a question as to the research on a Jtable using Jtextfield.
When the person enters the Work name in Textfield and click Search, in Jtable is to appear the search result.
My question is this: How do I clean up Jtable and fill it with the bank search results? I have no idea how to do that...
My main:
package view;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import controller.EmprestimoControl;
import controller.EmprestimoTableClick;
import controller.EmprestimoTableController;
import controller.EmprestimoTableModel;
import model.Emprestimo;
import java.awt.BorderLayout;
import javax.swing.JTable;
import javax.swing.ScrollPaneConstants;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.JButton;
public class TelaEmprestimo extends JFrame implements ActionListener, TableModelListener, ListSelectionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
private JFrame frame;
private JPanel contentPane;
private JTable table = new JTable();
private JTextField txtPesquisar = new JTextField();
private JButton btnPesquisar = new JButton("Pesquisar");
private JButton btnNovoEmp = new JButton("Novo Empréstimo");
private JLabel lblPesquisarObra = new JLabel("Obra");
private SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
private EmprestimoControl controle = new EmprestimoControl();
/**
* Launch the application.
*/
public static void main(String[] args){
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
TelaEmprestimo frame = new TelaEmprestimo();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public TelaEmprestimo() {
try {
initialize();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* Initialize the contents of the frame.
* @throws ClassNotFoundException
*/
private void initialize() throws ClassNotFoundException {
frame = new JFrame();
frame.setBounds(100, 100, 700, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
setResizable(false);
setTitle("Consulta e cadastro de empréstimos");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 550, 463);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
table.setBounds(10, 180, 674, 280);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setBounds(10, 80, 524, 330);
contentPane.add(scrollPane);
Object[][] dados = new Object[][]{};
scrollPane.setViewportView(table);
String[] cabecalho = new String[4];
cabecalho[0] = "Código";
cabecalho[1] = "Nome da Obra";
cabecalho[2] = "Disponibilidade";
cabecalho[3] = "Data de devolução";
DefaultTableModel model = new EmprestimoTableModel(dados, cabecalho);
table.setModel(model);
EmprestimoTableController empController = new EmprestimoTableController(model);
table.getColumnModel().getColumn(0).setPreferredWidth(20);
table.getColumnModel().getColumn(1).setPreferredWidth(200);
table.getColumnModel().getColumn(2).setPreferredWidth(50);
try {
empController.preencheTable();
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e.getMessage(), "ERRO", JOptionPane.ERROR_MESSAGE);
}
lblPesquisarObra.setHorizontalAlignment(SwingConstants.LEFT);
lblPesquisarObra.setBounds(10, 35, 74, 14);
contentPane.add(lblPesquisarObra);
txtPesquisar.setBounds(95, 29, 140, 20);
contentPane.add(txtPesquisar);
txtPesquisar.setColumns(10);
btnNovoEmp.setBounds(352, 28, 155, 23);
contentPane.add(btnNovoEmp);
btnNovoEmp.addActionListener(this);
btnPesquisar.setBounds(253, 28, 89, 23);
contentPane.add(btnPesquisar);
btnPesquisar.addActionListener(this);
}
public void emprestimoToForm( Emprestimo emp ){
txtPesquisar.setText(emp.getObra().getTipoObra());
}
@Override
public void actionPerformed(ActionEvent e) {
String cmd = e.getActionCommand();
if ("Pesquisar".equals(cmd)){
try {
List<Emprestimo> lista = controle.listaEmprestimos( txtPesquisar.getText() );
if (lista.size() > 0) {
emprestimoToForm(lista.get(0));
}
table.invalidate();
table.revalidate();
} catch (Exception e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(null,
"Erro ao pesquisar no banco de dados " + e1.getMessage());
}
} else if ("Novo Empréstimo".equals(cmd)) {
}
}
@Override
public void tableChanged(TableModelEvent e) {
int indice = e.getFirstRow();
Emprestimo emp = controle.getEmprestimo().get( indice );
emprestimoToForm( emp );
}
@Override
public void valueChanged(ListSelectionEvent e) {
if ( e.getValueIsAdjusting() ) {
int indice = table.getSelectionModel().getAnchorSelectionIndex();
System.out.println( "Foi selecionada a linha : " + indice );
Emprestimo emp = controle.getEmprestimo().get( indice );
emprestimoToForm( emp );
}
}
}
Tablemodel:
package controller;
import javax.swing.table.DefaultTableModel;
public class EmprestimoTableModel extends DefaultTableModel {
/**
*
*/
private static final long serialVersionUID = 1L;
public EmprestimoTableModel(Object[][] dados, String[] cabecalho){
super.setDataVector(dados, cabecalho);
}
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
}
Consultation:
package persistence;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import model.Emprestimo;
public class EmprestimoDao implements IEmprestimoDao {
private Connection c;
private Emprestimo emprestimo = new Emprestimo();
public EmprestimoDao () throws ClassNotFoundException, SQLException{
IGenericDao gDao = new GenericDao();
c = gDao.getConnection();
}
public List<Emprestimo> pesquisarObras(String nomeObras ) throws SQLException {
String sql = "SELECT emp.cod_obra AS id_obra, ob.titulo, emp.dispo, emp.dataDevolu "
+ "FROM emprestimo emp INNER JOIN obra ob ON ob.cod_obra = emp.cod_obra "
+ "WHERE ob.titulo LIKE '%"+nomeObras+"%' "
+ "ORDER BY id_obra";
PreparedStatement pst = c.prepareStatement( sql );
ResultSet rs = pst.executeQuery();
pst.setInt(1, emprestimo.getObra().getCodObra());
List<Emprestimo> emprestimo = new ArrayList<Emprestimo>();
while(rs.next()){
Emprestimo e = new Emprestimo();
e.getObra().setCodObra(rs.getInt("id_obra"));
e.getObra().setTitulo(rs.getString("titulo"));
e.setDisp(rs.getString("dispo"));
e.setDataDevolucao(rs.getDate("dataDevolu"));
emprestimo.add(e);
}
rs.close();
pst.close();
return emprestimo;
}
}
The Controller of the table:
package controller;
import java.sql.SQLException;
import java.util.List;
import javax.swing.table.DefaultTableModel;
import model.Emprestimo;
import persistence.EmprestimoDao;
import persistence.IEmprestimoDao;
public class EmprestimoTableController {
private DefaultTableModel model;
public EmprestimoTableController(DefaultTableModel model) {
this.model = model;
}
public void preencheTable() throws SQLException, ClassNotFoundException{
IEmprestimoDao mDao = new EmprestimoDao();
List<Emprestimo> listaEmprestimos = mDao.pesquisar();
model.setRowCount(0);
for(Emprestimo m: listaEmprestimos){
Object[] linha = new Object[4];
linha[0] = m.getObra().getCodObra();
linha[1] = m.getObra().getTitulo();
linha[2] = m.getDisp();
linha[3] = m.getDataDevolucao();
model.addRow(linha);
}
}
Related: Update a Jtable that is in a Jframe from a Jdialog
– user28595
And add the code of how you are filling the table and how the query is done in the question.
– user28595
Oops, I’ll do that. I just forgot haha
– Vinícius Novelli
Just set the tablemodel again, but the way the code is. I don’t even know how to suggest this, you didn’t add or explain how your tablemodel is.
– user28595
Okay, I’ll add the rest
– Vinícius Novelli
Maybe if you customize your tableModel making it receive a List, it is much easier this operation.
– user28595