Get line from JTable after Filter Data

1

I am using a TableModel (not the DefaultTableModel ) that populate with data from banco ( MySQL ), also use a Class to filter through a JTextField . It is working correctly, but I would like, after filtering through the data entered in the JTextField , to be able to select only the data that "left" in JTable . For the moment I select the first line after the filter, and I have as a return the first line of the original model (through the mouseClicked event). The image below illustrates, perhaps, more clearly:

Ithinkyouhavetosomehow"create a new modelo with the resulting data after the filter". Can anyone help to adapt this same class, or with information so that I can reach my goal? Many thanks!

Class to make the filter:

package Converter;

import javax.swing.JTable;
import javax.swing.RowFilter;
import javax.swing.table.TableRowSorter;
import org.jdesktop.beansbinding.Converter;


public class RowSorterToStringConverter extends Converter {

    private JTable table;

    public JTable getTable() {
        return table;
    }

    public void setTable(JTable table) {
        this.table = table;
    }

    @Override
    public Object convertForward(Object value) {
        return value.toString();
    }

    @Override
    public Object convertReverse(Object mask) {
        TableRowSorter sorter = new TableRowSorter(table.getModel());

        String m = mask.toString();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < m.length(); i++) {
            char c = m.charAt(i);
            sb.append('[').append(Character.toLowerCase(c)).append(Character.toUpperCase(c)).append(']');
        }
        sorter.setRowFilter(RowFilter.regexFilter(".*" + sb + ".*"));
        return sorter;
    }
}

Linking JTextField to Classe RowSorter

Mouseevent:

privatevoidjtableCLicked(){saveButton.setEnabled(false);Condutorcondutor=modelo.getCondutor(jTableCondutor.getSelectedRow());condutorIdField.setText((String.valueOf(condutor.getId())));condutorNomeField.setText(condutor.getNome());jCSetorDescr.setSelectedItem(condutor.getSetor());jCPessoaDescr.setSelectedItem(condutor.getPessoa());jCEmpresaDescr.setSelectedItem(condutor.getEmpresa());jCStatusDescr.setSelectedItem(condutor.getStatus());botoesEdicao();}

Update:

I'vemadethefollowingchanges:

privatevoidjTextFieldBuscaKeyReleased(java.awt.event.KeyEventevt){StringstringBusca=jTextFieldBusca.getText();filter(stringBusca);}privatevoidfilter(StringstringBusca){TableRowSorter<TableModel>tr=newTableRowSorter<TableModel>(modelo);jTableCondutor.setRowSorter(tr);tr.setRowFilter(RowFilter.regexFilter(stringBusca));}privatevoidjtableCLicked(){if(jTableCondutor.getRowSorter()!=null){try{introwSel=jTableCondutor.getSelectedRow();intindexRowModel=jTableCondutor.getRowSorter().convertRowIndexToModel(rowSel);Condutorcondutor=modelo.getCondutor(indexRowModel);condutorIdField.setText((String.valueOf(condutor.getId())));condutorNomeField.setText(condutor.getNome());jCSetorDescr.setSelectedItem(condutor.getSetor());jCPessoaDescr.setSelectedItem(condutor.getPessoa());jCEmpresaDescr.setSelectedItem(condutor.getEmpresa());jCStatusDescr.setSelectedItem(condutor.getStatus());botoesEdicao();}catch(Exceptione){System.out.println("Erro " + e.getMessage());
            }

        }
        else{
            try{
             Condutor condutor = modelo.getCondutor(jTableCondutor.getSelectedRow());
                condutorIdField.setText((String.valueOf(condutor.getId())));
                condutorNomeField.setText(condutor.getNome());
                jCSetorDescr.setSelectedItem(condutor.getSetor());
                jCPessoaDescr.setSelectedItem(condutor.getPessoa());
                jCEmpresaDescr.setSelectedItem(condutor.getEmpresa());
                jCStatusDescr.setSelectedItem(condutor.getStatus());
                botoesEdicao();
            } catch (Exception e) {
                System.out.println("Erro " + e.getMessage());
            }
        }
    }

Now it's all the way that I needed, except that after filtering, in this case only "a few lines remain in JTable ," if I edit a line (a objeto / p>

java.lang.IndexOutOfBoundsException:invalid range

After editing I call these two methods:

 public void limpaLista() {
        if (condutores.size() > 0) {
            int i = condutores.size();
            condutores.clear();
            fireTableRowsDeleted(0, i - 1);
        }
    }

public void preencherTabela() {
        CondutorDao condutorDao = new CondutorDao();
        modelo.adicionaLista(condutorDao.consultarCondutores());
    }

Update 2:

I've created these code snippets:

 private void jTBuscarRegistroKeyReleased(java.awt.event.KeyEvent evt) {                                             
        tr.setRowFilter(RowFilter.regexFilter("(?i)" + jTBuscarRegistro.getText()));
    }                                            

    class MyListSelectionListener implements ListSelectionListener {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            ListSelectionModel lsm = (ListSelectionModel) e.getSource();
            if (!lsm.isSelectionEmpty()) {

                try {
                    int rowSel = jTableCondutor.getSelectedRow();
                    int indexRowModel = jTableCondutor.getRowSorter().convertRowIndexToModel(rowSel);
                    Condutor condutor = modelo.getCondutor(indexRowModel);
                    condutorIdField.setText((String.valueOf(condutor.getId())));
                    condutorNomeField.setText(condutor.getNome());
                    jCSetorDescr.setSelectedItem(condutor.getSetor());
                    jCPessoaDescr.setSelectedItem(condutor.getPessoa());
                    jCEmpresaDescr.setSelectedItem(condutor.getEmpresa());
                    jCStatusDescr.setSelectedItem(condutor.getStatus());
                    botoesEdicao();
                } catch (Exception ee) {
                    System.out.println("Erro Ao Carregar Dados " + ee.getMessage());
                }

            }
        }
    ;

    }

And in the constructor:

jTableCondutor.setRowSorter(tr);
        jTableCondutor.getSelectionModel().addListSelectionListener(new MyListSelectionListener());

Now it worked correctly, without Exception , being able to select after the filter, and when it clears the JTextField of the search, it returns the original template with the changes made in the lines.     

asked by anonymous 29.06.2016 / 03:57

1 answer

0

To retrieve the selected row in a JTable , you need to call the convertRowIndexToModel ", passing the index of the selected row in the table as a parameter, something like this:

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

This way you avoid problems with IndexOfBoundException when trying to manipulate table row indices.

Assuming that modelo.getCondutor is some method of your TableModel that retrieves an object from the index passed, pass the indexRowModel as a parameter:

private void jtableCLicked() {
        ...

        int rowSel = suaTable.getSelectedRow();
        int indexRowModel = suaTable.getRowSorter().convertRowIndexToModel(rowSel);
        Condutor condutor = modelo.getCondutor(indexRowModel);

        ...
    }

How do you want to pick the selected row as some one is selected in the table, rather than using a mouse clicker listener that may not work if the user changes the selected row via keyboard, a better solution is to override the valueChanged , adding ListSelectionlistener to your table:

suaTable.getSelectionModel().addListSelectionListener(new ListSelectionListener(){

    @Override
    public void valueChanged(ListSelectionEvent e) {

        ListSelectionModel lsm = (ListSelectionModel) e.getSource(); 

        if(!lsm.isSelectionEmpty()){

        //aqui você insere a ação que quer fazer quando
        //uma linha for selecionada ou uma seleção for
        //alterada na tabela
        }
    }
}

In this way, if a selection is made or changed, regardless of whether it was done by mouse click or the keyboard arrows, it will call this method.

Reference:

How to Write a List Selection Listener (oracle)

    
29.06.2016 / 14:25