Jtable search does not return as expected

Asked

Viewed 85 times

-1

I have a bug I don’t understand. The idea is simple, I should type a value in a field and it returns me in the table, this happens, but when I click on the value found in the search it selects me the first value within the table

import java.awt.Color;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.List;

import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.RowFilter;
import javax.swing.border.LineBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableRowSorter;

import br.sp.mogi.imperiocongelados.model.Client;
import br.sp.mogi.imperiocongelados.model.tables.ModelTableClient;

public class Teste extends JFrame 
{
    public Teste() 
    {
        inicializarComponentes();
        inicializarEventos();
    }

    private void inicializarComponentes() 
    {
        setTitle("Teste");
        setSize(490, 600);
        setResizable(false);
        setLocationRelativeTo(null);
        setLayout(null);
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        // Search
        JTextField txtSearchForCode = new JTextField();
        txtSearchForCode.setToolTipText("Busca por codigo");
        txtSearchForCode.setLocation(10, 10);
        txtSearchForCode.setSize(50, 25);
        add(txtSearchForCode);

        // Table
        JTable table = new JTable();
        table.setBackground(Color.WHITE);

        JScrollPane scroll = new JScrollPane(table);
        scroll.setBorder(new LineBorder(Color.BLACK));
        scroll.setLocation(10, txtSearchForCode.getY() + txtSearchForCode.getHeight() + 1);
        scroll.setSize(470, 540);
        scroll.getViewport().setBackground(Color.WHITE);
        add(scroll);

    }

    private void searchForCode()
    {
        ModelTableClient tableClient = (ModelTableClient) table.getModel();

        final TableRowSorter<ModelTableClient> sorter = new TableRowSorter<ModelTableClient>(tableClient);

        table.setRowSorter(sorter);

        String searchForCode = txtSearchForCode.getText();

        if(searchForCode.length() == 0)
        {
            sorter.setRowFilter(null);
        }
        else
        {
            try 
            {
                RowFilter<ModelTableClient, Object> rf = null;

                try
                {
                    rf = RowFilter.regexFilter(searchForCode, 0);
                }
                catch(java.util.regex.PatternSyntaxException e)
                {
                    return;
                }

                sorter.setRowFilter(rf);
            } 
            catch (Exception e) 
            {
                JOptionPane.showMessageDialog(this, "Erro de busca por codigo", "Erro", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    public void completeFields()
    {
        txtName.setText(selectedClient.getName());

        String dateText = dateFormat.format(selectedClient.getRegistrationDate());
        ftRegistrationDate.setText(dateText);

        ftDocument.setText(selectedClient.getDocument());

        ftZipCode.setText(selectedClient.getZipCode());
        txtState.setText(selectedClient.getState());
        txtCity.setText(selectedClient.getCity());
        txtNeighborhood.setText(selectedClient.getNeighborhood());
        txtStreet.setText(selectedClient.getStreet());
        ftNumber.setText(selectedClient.getNumber());

        ftLandLine.setText(selectedClient.getLandline());
        ftCellphone.setText(selectedClient.getCellPhone());

        ftRoute.setText(selectedClient.getRoute());
    }

    private void inicializarEventos() 
    {
        // Select row on table
            table.getSelectionModel().addListSelectionListener(new ListSelectionListener() 
            {

                @Override
                public void valueChanged(ListSelectionEvent e) 
                {
                        int row = table.getSelectedRow();
                        if(row >= 0 && row < clientList.size())
                        {
                            selectedClient = clientList.get(row);
                            completeFields();
                        }
                }
            });

            // Search
            txtSearchForCode.addKeyListener(new KeyAdapter() 
            {
                @Override
                public void keyReleased(KeyEvent e) 
                {
                    searchForCode();
                }
            });

    }
}
  • Possible duplicate of Apply filters to a Jtable

  • I added the full view client code

  • Mine performs the search, but when I click on it it pulls the first result, not what I sought

  • That code is not a [mcve], has dependencies on other classes. Remove all dependencies, leave only what is necessary for the error to be reproducible. Read how to do this in the link I mentioned. Take advantage and read the answers that Linkei, have examples of filters identical to what you are doing.

  • I think now is what is necessary, I left only the functions he needs to perform the search and the code with the name of the fields along with the constructor

  • The code still runs on dependencies, you just cut the Imports. Please read the first link to learn how to provide a minimal, complete and verifiable example.

  • I have read and left only the dependencies that the search uses which is from the table template

  • Restart from scratch. Create a new program, and only include what is necessary to reproduce the problem.

  • I’m not an expert, I think that’s it

Show 6 more comments

1 answer

5


You did not provide a Minimum, Complete and Verifiable Example, but I suspect the cause is table and model filter index conflict.

When making a filter in a table, you need to convert the filter input to the equivalent of the model’s Dice in order to be able to retrieve the filtered line correctly:

int rowSel = suaTable.getSelectedRow();//pega o indice da linha na tabela
int indexRowModel = suaTable.getRowSorter().convertRowIndexToModel(rowSel);//converte pro indice do model

More information you can read in the links I left related in the question and nestra another answer, or providing a Minimum, Complete and Verifiable Example correctly so that it is possible to analyze the problem better.

  • 1

    It worked as expected, I break a branch. Thank you

Browser other questions tagged

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