Apply filters to a Jtable

Asked

Viewed 1,662 times

4

I have a table and in a JPANEL on top of it I created textFields and combobox with the intention of using them as filter. The method:

tableRowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + busca));

It waits for a string as a filter?
If the filter has more than one parameter how do I use it?

My screen is like this:

inserir a descrição da imagem aqui

It would be something like Example:

public class teste2 extends javax.swing.JFrame {

// Variaveis                
private javax.swing.JButton btnAplicar;
private javax.swing.JButton btnLimpar;
private javax.swing.JComboBox comboboxCategoria;
private javax.swing.JComboBox comboboxStatus;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JLabel lblAbertura;
private javax.swing.JLabel lblCategoria;
private javax.swing.JLabel lblCliente;
private javax.swing.JLabel lblNumero;
private javax.swing.JLabel lblResponsavel;
private javax.swing.JLabel lblStatus;
private javax.swing.JLabel lblUsuario;
private javax.swing.JTable tableServicosAbertos;
private javax.swing.JFormattedTextField txtAbertura;
private javax.swing.JTextField txtCliente;
private javax.swing.JFormattedTextField txtNumero;
private javax.swing.JTextField txtResponsavel;
private javax.swing.JTextField txtUsuario;

public teste2() {
    iniciarComponentes();

}

private void iniciarComponentes() {

    jScrollPane2 = new javax.swing.JScrollPane();
    tableServicosAbertos = new javax.swing.JTable();
    comboboxStatus = new javax.swing.JComboBox();
    lblCategoria = new javax.swing.JLabel();
    lblStatus = new javax.swing.JLabel();
    txtAbertura = new javax.swing.JFormattedTextField();
    lblAbertura = new javax.swing.JLabel();
    lblUsuario = new javax.swing.JLabel();
    lblResponsavel = new javax.swing.JLabel();
    txtUsuario = new javax.swing.JTextField();
    txtResponsavel = new javax.swing.JTextField();
    lblCliente = new javax.swing.JLabel();
    txtCliente = new javax.swing.JTextField();
    txtNumero = new javax.swing.JFormattedTextField();
    lblNumero = new javax.swing.JLabel();
    comboboxCategoria = new javax.swing.JComboBox();
    btnAplicar = new javax.swing.JButton();
    btnLimpar = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    setTitle("SiGS - Sistema de gerenciamento de serviços");
    setMinimumSize(new java.awt.Dimension(1366, 768));
    setResizable(false);
    addWindowListener(new java.awt.event.WindowAdapter() {
        public void windowActivated(java.awt.event.WindowEvent evt) {

        }
    });

    tableServicosAbertos.setModel(new javax.swing.table.DefaultTableModel(
            new Object[][]{
                {"OS20160214", "SAS", "Redes", "20/11/2016", "Max Vargas", "Max Vargas", "Aberto"},
                {"OS20160242", "Multiserv", "Computadores", "15/07/2016", "Max Vargas", "Mateus Nascimento", "Fechado"},
                {"OS20165851", "Telecom", "CFTV", "16/07/2016", "Max Vargas", "Fabio Oliv.", "Fechado"},
                {null, null, null, null, null, null, null}
            },
            new String[]{
                "Numero", "Cliente", "Categoria", "Abertura", "Usuario", "Responável", "Status"
            }
    ));
    jScrollPane2.setViewportView(tableServicosAbertos);

    comboboxStatus.setModel(new javax.swing.DefaultComboBoxModel(new String[]{" ", "Aberto", "Fechado", "Cancelado", "Pausado"}));

    lblCategoria.setText("Categoria:");

    lblStatus.setText("Status:");

    lblAbertura.setText(" Abertura:");

    lblUsuario.setText("Usuário:");

    lblResponsavel.setText("Responsável:");

    lblCliente.setText("Cliente:");

    lblNumero.setText("Número:");

    comboboxCategoria.setModel(new javax.swing.DefaultComboBoxModel(new String[]{" ", "Computadores", "CFTV", "Redes", "Telefonia", "Outros"}));

    btnAplicar.setText("OK");

    btnLimpar.setText("Limpar");

    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()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                    .addGap(0, 0, Short.MAX_VALUE)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addGroup(layout.createSequentialGroup()
                                                    .addGap(10, 10, 10)
                                                    .addComponent(lblStatus)
                                                    .addGap(15, 15, 15)
                                                    .addComponent(comboboxStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                    .addGap(85, 85, 85)
                                                    .addComponent(lblResponsavel)
                                                    .addGap(5, 5, 5)
                                                    .addComponent(txtResponsavel, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE))
                                            .addGroup(layout.createSequentialGroup()
                                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                            .addGroup(layout.createSequentialGroup()
                                                                    .addComponent(lblCategoria)
                                                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                                                    .addComponent(comboboxCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                    .addGap(104, 104, 104)
                                                                    .addComponent(lblUsuario)
                                                                    .addGap(10, 10, 10)
                                                                    .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, 152, javax.swing.GroupLayout.PREFERRED_SIZE))
                                                            .addGroup(layout.createSequentialGroup()
                                                                    .addComponent(lblAbertura)
                                                                    .addGap(10, 10, 10)
                                                                    .addComponent(txtAbertura, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                    .addGap(105, 105, 105)
                                                                    .addComponent(lblCliente)
                                                                    .addGap(13, 13, 13)
                                                                    .addComponent(txtCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                                    .addGap(28, 28, 28)
                                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                            .addGroup(layout.createSequentialGroup()
                                                                    .addComponent(btnAplicar, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                                    .addComponent(btnLimpar))
                                                            .addGroup(layout.createSequentialGroup()
                                                                    .addComponent(lblNumero)
                                                                    .addGap(19, 19, 19)
                                                                    .addComponent(txtNumero, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                                    .addGap(78, 78, 78))
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING))
                    .addContainerGap())
    );
    layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addGap(90, 90, 90)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(lblCategoria)
                                    .addComponent(comboboxCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(lblUsuario)
                            .addComponent(txtUsuario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblNumero)
                            .addComponent(txtNumero, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(10, 10, 10)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(lblStatus)
                            .addComponent(comboboxStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(lblResponsavel)
                            .addComponent(txtResponsavel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                    .addGap(10, 10, 10)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addComponent(lblAbertura)
                                            .addComponent(txtAbertura, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(lblCliente)
                                            .addComponent(txtCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGap(46, 46, 46)
                                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                    .addGap(18, 18, 18)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                            .addComponent(btnAplicar)
                                            .addComponent(btnLimpar))))
                    .addContainerGap(241, Short.MAX_VALUE))
    );

    pack();
    setLocationRelativeTo(null);
}
  • Sorry for the delay, but at the same time I’m trying to make this filter I’m studying Framework Quartz. Is that my table is mounted at runtime by making a select of the Services in the bank using a library I picked up in a video lesson. Put here the class that does this + select?

  • Max, your code is not complete and is not yet executable, but does not have the print fields. Add the full class of your screen by removing this call method with the custom database and classes and adding this snippet with manual data. If it doesn’t fit, post to the Pastebin and add the link at the end of the question to the conference.

  • So was it? Here’s OK. Sorry. First time I put something here.

  • Have you tried running this code? Try it there, it is not executable.

  • Now Yes, as a test I created a file New Jframe File, paste the code and surround.

2 answers

4


After some tests, I was able to develop a solution that will make the search in a global way, covering eventual failures as when one of the fields is not informed, and also cleaning the filters, when all fields are erased.

Initially, you must create a variable TableRowSorter as class property, to be used in the table afterwards:

private TableRowSorter<TableModel> sorter;

From the code, I realized that you are creating the screen by the netbeans editor, so you will need to add the lines below, which refer to creating the RowSorter, in the constructor, after the method that creates its table (in this case, it is the iniciarComponentes();):

//...

iniciarComponentes();

//resgata o TableModel da sua JTable
TableModel model = tableServicosAbertos.getModel();
//Cria um RowSorter baseado no TableModel resgatado
sorter = new TableRowSorter<TableModel>(model);
//Aplica o RowSorte na na JTable
tableServicosAbertos.setRowSorter(sorter);

The method below is who will do all the filtering work in the table, treating each search field to the relative column in the table:

protected void setFilterInJTable() {


    String  numero = txtNumero.getText().trim(),
            cliente = txtCliente.getText().trim(),
            categoria = comboboxCategoria.getSelectedItem().toString().trim(),
            abertura = txtAbertura.getText().trim(),
            usuario = txtUsuario.getText().trim(), 
            responsavel = txtResponsavel.getText().trim(),
            status = comboboxStatus.getSelectedItem().toString().trim();

    //cria uma lista para guardar os filtros de cada coluna
    List<RowFilter<Object, Object>> filters = new ArrayList<RowFilter<Object, Object>>();
    filters.add(RowFilter.regexFilter("(?i)" + numero, 0));
    filters.add(RowFilter.regexFilter("(?i)" + cliente, 1));
    filters.add(RowFilter.regexFilter(categoria, 2));
    filters.add(RowFilter.regexFilter("(?i)" + abertura, 3));
    filters.add(RowFilter.regexFilter("(?i)" + usuario, 4));
    filters.add(RowFilter.regexFilter("(?i)" + responsavel, 5));
    filters.add(RowFilter.regexFilter(status, 6));
    //aplica os filtros no RowSorter que foi criado no construtor
    //utilizando o andFilter
    sorter.setRowFilter(RowFilter.andFilter(filters));

}

On the button Aplicar, just add a ActionListener and call the method setFilterInJTable() within the actionPerformed, that the research will be active.

See a print of the search result using the fields:

inserir a descrição da imagem aqui

The above method code takes all filter fields from the screen as String, removes blanks (to avoid unwanted results if one of the fields is not informed), and treats strings brought from text fields as case insensitive.

This filter can even meet your table, but there are fields that should not be treated as String, example are the date fields, if they come from the database as date, their types should be kept in the JTable.

Pointing out what was said in the other answer, perhaps the most indicated is the search to be done directly in the database, after all, the table data can be modified in the database by other instances of the application, and the search in this case will work with data that may not be the most current.

In this other answer there are some reference links to study regarding RowSorter.

  • Thank you very much, I tested it and it worked very well. I just have to try to tweak my code to get everything ok, because when I run now it does not mount the table with select and the burst array error. It must have to do with me being using dafaultModel right? I’ll try to learn how to make my own model.

  • @Maxvargas you can mark the answer as accepted by clicking on V her left, so she serves as a reference, as the other answer served you =)

3

I would always advise to do the query directly in the database, for the simple fact that at any minute, the information on the screen may have been updated/deleted and even entered new records. But if you want to use rowFilter, see example directly from the documentation:


List< RowFilter < Object, Object > > rfs =  new ArrayList < RowFilter < Object, Object > >);
filters.add(RowFilter.regexFilter("(?i)^Zac$"));
filters.add(RowFilter.regexFilter("(?i)^A$"));
RowFilter af = RowFilter.andFilter(rfs);

When I used, I remember having trouble with date fields. I believe you will have to do something similar to this:


RowFilter.dateFilter(ComparisonType.AFTER, new Date());
After that, add rowFilter to your table. Any questions, I’m available. (I haven’t dealt with Jtable for a while, any mistakes, edit my reply or correct me below. Thank you.

  • @diegofm I forgot to mention Sorter. Test with it too?

  • Could you situate me more or less like this? Would it be something like a select using a filter field as parameter? ai I would make 1 select for each field?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.