javaswingjtablerowfilterdocumentlistener

Dynamic search filter in JTable


This question is related to the one mentioned here: [I want to read from a txt file and write to an existing JTable

I have made a program which can read from a txt file and write onto a JTable. I have also created a method which allows me to dynamically searching the contents of the JTable and display the results that match the word. However, every new entry that I am writing at the JTable is able to be found from the filter. BUT when I load a txt file contents and try to use the search filter afterwards, the results cannot be displayed the the JTable disappears as soon as I start typing something on the text field.

My code for the search method is as follows:

//Creation and functionality of the Search Field

class TestTableSortFilter extends JPanel {
    public TableRowSorter < TableModel > rowSorter = new TableRowSorter < > (table.getModel());
    public JTextField searchFilter = new JTextField();
    public TestTableSortFilter() {
        table.setRowSorter(rowSorter);
        JPanel panel = new JPanel(new BorderLayout());
        panel.add(new JLabel("Search:"),
        BorderLayout.WEST);
        panel.add(searchFilter, BorderLayout.CENTER);
        setLayout(new BorderLayout());
        add(panel, BorderLayout.SOUTH);
        add(new JScrollPane(table), BorderLayout.CENTER);
        searchFilter.getDocument().addDocumentListener(new DocumentListener() {
            @Override
            public void insertUpdate(DocumentEvent e) {
                String text = searchFilter.getText();
                if (text.trim().length() == 0) {
                    rowSorter.setRowFilter(null);
                } else {
                    rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                }
            }
            @Override
            public void removeUpdate(DocumentEvent e) {
                String text = searchFilter.getText();
                if (text.trim().length() == 0) {
                    rowSorter.setRowFilter(null);
                } else {
                    rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
                }
            }
            @Override
            public void changedUpdate(DocumentEvent e) {
                throw new UnsupportedOperationException("Not supported yet.");
            }
        });
    } //end TestTableSortFilter
  } //end class table sort & creating the sorter for Search

Solution

  • on which class? The OpenData where I read from the txt file? there is the table.setModel(new DefaultTableModel(col,0)); line there. Is it the one that should be changed?

    Try something like this:

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    
    public class RowSorterTest {
      private final String[] columnNames = {"Number", "Type", "IP", "Protocol", "Line"};
      private final Object[][] data = {
        {"aaa", "1", "", "", ""}, {"bbbbb", "", "", "", ""}
      };
      private final DefaultTableModel model = new DefaultTableModel(data, columnNames) {
        @Override public Class<?> getColumnClass(int column) {
          return getValueAt(0, column).getClass();
        }
      };
      private final JTable table = new JTable(model);
      private final TableRowSorter<TableModel> rowSorter = new TableRowSorter<>(model);
      private final JTextField searchFilter = new JTextField();
      private final JButton open = new JButton("open");
    
      public JComponent makeUI() {
        table.setRowSorter(rowSorter);
        open.addActionListener(new OpenData());//end OpenData class
    
        JPanel panel = new JPanel(new BorderLayout());
        panel.add(new JLabel("Search:"), BorderLayout.WEST);
        panel.add(searchFilter, BorderLayout.CENTER);
        panel.add(open, BorderLayout.EAST);
    
        searchFilter.getDocument().addDocumentListener(new DocumentListener() {
          @Override
          public void insertUpdate(DocumentEvent e) {
            String text = searchFilter.getText();
            System.out.println(text);
            if (text.trim().length() == 0) {
              rowSorter.setRowFilter(null);
            } else {
              rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
            }
            table.repaint();
          }
          @Override
          public void removeUpdate(DocumentEvent e) {
            String text = searchFilter.getText();
            if (text.trim().length() == 0) {
              rowSorter.setRowFilter(null);
            } else {
              rowSorter.setRowFilter(RowFilter.regexFilter("(?i)" + text));
            }
          }
          @Override
          public void changedUpdate(DocumentEvent e) {
            //not needed: throw new UnsupportedOperationException("Not supported yet.");
          }
        });
    
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(table));
        p.add(panel, BorderLayout.SOUTH);
        return p;
      }
      class OpenData implements ActionListener {
        @Override public void actionPerformed(ActionEvent e) {
    //       String line = null;
    //       try{
    //           File file = new File ("C:\\Inne\\PhoneData.txt");
    //           FileReader fr = new FileReader (file.getAbsoluteFile());
    //           BufferedReader br = new BufferedReader (fr);
    //           StringBuilder builder = new StringBuilder();
    //           while ((line = br.readLine()) != null) {
    //               builder.append(line);
    //           }
    //           String[] lineArray= builder.toString().split("/");
    //           table.setModel(new DefaultTableModel(columnNames, 0));
    //           for(String currentLine: lineArray){
    //               String[] dataArray = currentLine.split(";");
    //               ((DefaultTableModel)table.getModel()).addRow(dataArray);
    //           }
    //           br.close();
    //       }catch (IOException e3) {
    //           e3.printStackTrace();
    //       }//end catch
          DefaultTableModel m = new DefaultTableModel(columnNames, 0);
          //Dummy data
          for (int i = 0; i < 5; i++) {
            String[] dataArray = {"aa" + i, "", "", "", ""};
            m.addRow(dataArray);
          }
          table.setModel(m);
          rowSorter.setModel(m);
        }//end action method
      }
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          @Override public void run() {
            createAndShowGUI();
          }
        });
      }
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new RowSorterTest().makeUI());
        f.setSize(320, 240);
        f.setLocationRelativeTo(null);
        f.setVisible(true);
      }
    }