title: Combine filters on a JTable author: depierre published: 2013-06-01 categories: Java keywords: project, swing, java, awt, jtable, filter, regex, trick Since few days, I'm working on a school project. Its goal is to use [Java](https://www.java.com/) and [Swing](https://en.wikipedia.org/wiki/Swing_%28Java%29) to create an interface for the [Crew Scheduling Problem](https://en.wikipedia.org/wiki/Crew_scheduling). Dealing with a list of tasks, I choose to use a [JTable](https://docs.oracle.com/javase/6/docs/api/javax/swing/JTable.html) as the graphical view. One feature I want to implement is some filters to display/hide the tasks. If you read the Java doc, you will see a lot of examples on [how to use filters](https://docs.oracle.com/javase/tutorial/uiswing/components/table.html#sorting). My problem here is that these examples only deals with simple filter, i.e. one filter for the whole row. What I need is several filters, each one for a specific cell on a row. At this point, the doc becomes useless. Hopefully, while looking for some similar issues on the Internet, I stumble on [really few topics](http://pulkitsinghal.blogspot.fr/2010/06/multiple-row-filters-for-jtable.html) which explain how to perform a more advanced filtering system. Therefore I am writing this post to sum them up. With a JTable, you can not straightfully create several filters and ask Swing to appy each one on a specific cell (lame!). But what you can do is create a list of RowFilter and then combine them using a [RowFilter.andFilter](https://docs.oracle.com/javase/6/docs/api/javax/swing/RowFilter.html#andFilter%28java.lang.Iterable%29). :::java /* Match the filter with the column 0 */ final RowFilter firstFilter = RowFilter.regexFilter(firstFilter, 0); /* Match the filter with the column 1 */ final RowFilter secondFilter = RowFilter.regexFilter(secondFilter, 1); /* Match the filter with the column 2 */ final RowFilter thirdFilter = RowFilter.regexFilter(thirdFilter, 2); final List> filters = new ArrayList>(); filters.add(firstFilter); filters.add(secondFilter); filters.add(thirdFilter); /* The row must match every filters */ final RowFilter compoundRowFilter = RowFilter.andFilter(filters); final TableRowSorter sorter = new TableRowSorter(); sorter.setRowFilter(compoundRowFilter); final JTable tasksTable = new JTable(); tasksTable.setRowSorter(sorter); The code above shows the principle using three filters and an 'and' clause. Hence only the row matching every filters will be shown. In my project, I use JComboBox to let the user decides. Using this system of multiple filters, a result may look like below. ![JTable without filter](/static/images/jtable/zero_filter.png) ![JTable with two filters](/static/images/jtable/two_filters.png) ![JTable with three filters](/static/images/jtable/three_filters.png) Hopefully, I don't have to filter tons of columns \o/