Search using JTextField and JTable

1

I am having a question about searching a JTable using JTextField.

When the person enters the name of the Work in Textfield and click on search, in the JTable is to appear the search result.

Myquestionisthis:HowdoIcleanJTableandfillitoutwiththesearchresultintheBank?Ihavenoideahowtodothis...

Mymain:

packageview;importjava.awt.EventQueue;importjava.awt.event.ActionEvent;importjava.awt.event.ActionListener;importjava.awt.event.MouseListener;importjava.sql.SQLException;importjava.text.SimpleDateFormat;importjava.util.List;importjavax.swing.JFrame;importjavax.swing.JOptionPane;importjavax.swing.JPanel;importjavax.swing.JScrollPane;importjavax.swing.border.EmptyBorder;importjavax.swing.event.ListSelectionEvent;importjavax.swing.event.ListSelectionListener;importjavax.swing.event.TableModelEvent;importjavax.swing.event.TableModelListener;importjavax.swing.table.DefaultTableModel;importcontroller.EmprestimoControl;importcontroller.EmprestimoTableClick;importcontroller.EmprestimoTableController;importcontroller.EmprestimoTableModel;importmodel.Emprestimo;importjava.awt.BorderLayout;importjavax.swing.JTable;importjavax.swing.ScrollPaneConstants;importjavax.swing.JLabel;importjavax.swing.JTextField;importjavax.swing.SwingConstants;importjavax.swing.UIManager;importjavax.swing.JButton;publicclassTelaEmprestimoextendsJFrameimplementsActionListener,TableModelListener,ListSelectionListener{/****/privatestaticfinallongserialVersionUID=1L;privateJFrameframe;privateJPanelcontentPane;privateJTabletable=newJTable();privateJTextFieldtxtPesquisar=newJTextField();privateJButtonbtnPesquisar=newJButton("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;
    }

}

Inquiry:

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 table's Controll:

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);
            }
    }
    
asked by anonymous 12.06.2016 / 04:04

1 answer

2

Hello,

I do not know if this is the best way, but I used the following steps once:

1 - Clear table lines: model.setNumRows (0);

2 - Run the search (use Prepare Statement): "SELECT * FROM Sua Tabela WHERE Seu campo LIKE?" - for example

3- Popular a table (use your bank table fields):

while(resultSet.next()) {
  model.addRow(new Object[] {
    resultSet.getInt("id");
    resultSet.getString("nomeObra");
    resultSet.getString("disponibilidade");
    resultSet.getString("dataDevolucao");
  });
}

I hope I have helped.

    
12.06.2016 / 04:52