JTable中的动态搜索过滤器

时间:2015-07-13 09:05:57

标签: java swing jtable rowfilter documentlistener

这个问题与这里提到的问题有关: [I want to read from a txt file and write to an existing JTable

我制作了一个可以从txt文件中读取并写入JTable的程序。我还创建了一个方法,允许我动态搜索JTable的内容并显示与单词匹配的结果。 但是,我在JTable中编写的每个新条目都可以从过滤器中找到。但是,当我加载txt文件内容并尝试使用搜索过滤器后,只要我开始在文本字段中输入内容,JTable就会消失,结果无法显示。

我的搜索方法代码如下:

//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

1 个答案:

答案 0 :(得分:2)

  

在哪个班级?我从txt文件中读取的OpenData?有table.setModel(new DefaultTableModel(col,0));在那里。是应该改变的吗?

尝试这样的事情:

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);
  }
}