简体   繁体   English

如何过滤 JTable 中的行?

[英]How can I filter rows in a JTable?

I have a JTable with many strings in it.我有一个 JTable 里面有很多字符串。 I have created a textbox for user entry, above the table.我在表格上方创建了一个用于用户输入的文本框。 I want a row filter which can remove the rows having strings entered by the user in the text box.我想要一个行过滤器,它可以删除用户在文本框中输入的字符串的行。 Please help me out for this.请帮我解决这个问题。

from here: 从这里:
sorting and filtering 排序和过滤

In the following example code, you explicitly create a sorter object so you can later use it to specify a filter: 在以下示例代码中,您显式创建了一个分类器对象,以便稍后使用它来指定过滤器:

 MyTableModel model = new MyTableModel(); sorter = new TableRowSorter<MyTableModel>(model); table = new JTable(model); table.setRowSorter(sorter); 

Then you filter based on the current value of a text field: 然后根据文本字段的当前值进行过滤:

 private void newFilter() { RowFilter<MyTableModel, Object> rf = null; //If current expression doesn't parse, don't update. try { rf = RowFilter.regexFilter(filterText.getText(),0); } catch (java.util.regex.PatternSyntaxException e) { return; } sorter.setRowFilter(rf); } 

This few line solution seems to work: 这几行解决方案似乎有效:

private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) 
{                                            
    TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(((DefaultTableModel) jTable1.getModel())); 
    sorter.setRowFilter(RowFilter.regexFilter(jTextField1.getText()));

    jTable1.setRowSorter(sorter);
}  

您可以使用JTable.setAutoCreateRowSorter ,它将使用JTable的默认行分类器/过滤器

To pick up the comment from kd304, you could use GlazedLists . 要从kd304中获取评论,您可以使用GlazedLists There you'll use a FilterList as the input for your JTable, and the FilterList will take care of the rest. 在那里,您将使用FilterList作为JTable的输入,FilterList将负责其余部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM