简体   繁体   中英

JTable rowfilter between two dates, same column

How can I implement a RowFilter between two dates? The dates are in string format. Is it necessary to change the format to a date format to apply a RegexFilter ?

I tried using the following, but failed :

DefaultTableModel model = (DefaultTableModel) easypath.masteBusiness_table.getModel();
easypath.masteBusiness_table.setModel(model);
TableRowSorter<TableModel> rowSorter = new TableRowSorter<>(easypath.masteBusiness_table.getModel());
easypath.masteBusiness_table.setRowSorter(rowSorter);
rowSorter.setRowFilter(RowFilter.regexFilter(startD+"\\s+(.*?)\\s+"+endD));

I know I am wrong with the filtering as (startD+"\\\\s+(.*?)\\\\s+"+endD)); is only for searching a single string but as a novice I would very much appreciate any suggestion.

UPDATE
I just saw this ( http://docs.oracle.com/javase/7/docs/api/javax/swing/RowFilter.html ) where RowSorter<M,I> , M is the model and I is an integer value, which does not match my criteria

You should be storing a Date in the TableModel not a String representation of the date.

Then you can use a RowFilter .

Instead of a regex filter you can use an "and" filter with two date filters. Something like:

List<RowFilter<Object,Object>> filters = new ArrayList<RowFilter<Object,Object>>(2);
filters.add( RowFilter.dateFilter(ComparisonType.AFTER, startDate) );
filters.add( RowFilter.dateFilter(ComparisonType.BEFORE, endDate) );
rf = RowFilter.andFilter(filters);
sorter.setRowFilter(rf);

Read the Swing tutorial on Sorting and Filtering for more information and working examples on how to use a filter.

You should have an atributte JTable table and DefaultTableModel dtm . Then in the function to filter by a range of dates.

public void filter(Date startDate, Date endDate){
    List<RowFilter<Object,Object>> filters = new ArrayList<RowFilter<Object,Object>>(2);
    filters.add( RowFilter.dateFilter(ComparisonType.AFTER, startDate) );
    filters.add( RowFilter.dateFilter(ComparisonType.BEFORE, endDate) );
    dtm = (DefaultTableModel) table.getModel();
    TableRowSorter<DefaultTableModel> tr = new TableRowSorter<>(dtm);
    table.setRowSorter(tr);
    RowFilter<Object, Object> rf = RowFilter.andFilter(filters);
    tr.setRowFilter(rf);}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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