Фильтр строк JTable на основе списка целых чисел строк модели таблицы - PullRequest
0 голосов
/ 21 февраля 2020

Я создаю экран запроса для моей таблицы данных. Я выполнил работу и консолидировал строки, которые я хочу показать в таблице, основываясь на пользовательских критериях.

Как применить фильтр строк к таблице на основе строк модели? Например: я хочу показать строки 3,6,7,8,9, которые хранятся в ArrayList<Integer> list.

. В настоящее время я не понимаю класс RowFilter. Я не уверен, что делать или как это использовать здесь:

RowFilter<DefaultTableModel,Integer> rf = new RowFilter<>() {
    @Override
    public boolean include(Entry entry) {
        // TODO Auto-generated method stub
        return false;
    }
};

Ответы [ 2 ]

1 голос
/ 21 февраля 2020

Возможно, вы найдете приведенный ниже метод несколько полезным. Я использую его для фильтрации JTables. Вам нужно использовать класс TableRowSorter:

<code>/**
 * Make sure the supplied JTable's DefaultTableModel already contains data
 * before calling this method.
 * <p>
 * The JTable always retains the data it is currently filled with within its
 * Table Model. <b>Knowing this we can theoretically fill the Table with all
 * database table records then use the Filter to display only the specific
 * table records we want.</b> This way we don't have to pole the database
 * for different records all the time and records acquisition is greatly
 * increased.
 * <p>
 * This method will pass the supplied Filter text across the supplied JTable
 * and will force that JTable to only display records (contained within that
 * JTable at the time) which contains that specific text. It reacts very
 * much like a search engine for the JTable.
 * <p>
 * If you want to display all records again which were originally contained
 * within the supplied JTable then just pass a Null String ("") within the
 * searchCriteria parameter of this method.
 *
 * @param table          (JTable) The JTable to run filter on.<br>
 *
 * @param searchCriteria (String) The text to filter JTable with. Passing a
 *                       Null String ("") will force the table to display
 *                       all records. Regular Expressions (RegEx) can also
 *                       be supplied within the criteria string. If the
 *                       wildcard characters <b>?</b> or <b>*</b> are
 *                       supplied within the filter criteria String without
 *                       any RegEx meta characters then the functional
 *                       purpose of these two wildcard characters are
 *                       converted to RegEx when encountered. If actual
 *                       Regular Expressions are going to be used to make up
 *                       the search criteria string then be sure to set the
 *                       <b>endorseWildcards</b> optional parameter to
 *                       boolean false since the <b>?</b> and <b>*</b>
 *                       wildcard characters have different meaning within a
 *                       Regular Expression and must be handled
 *                       differently.<br>
 *
 * @param options        (optional - Integer/Boolean):<pre>
 *
 *     byColumnNumber - (Optional - Integer - Default is -1) By default
 *                       this method filters across all table columns but
 *                       you can be column specific if you pass a column
 *                       number to this optional parameter. This parameter
 *                       accepts only a <b>Literal Column Number</b> which
 *                       means that although the first column within a
 *                       JTable is considered column 0, to this method it is
 *                       considered as column 1.
 *
 *    endorseWildcards - (boolean) Default is true (allow wildcards). If true
 *                       then when a wildcard character is encountered within
 *                       a search criteria string it is automatically converted
 *                       to its RegEx equivalent. The two wildcard characters
 *                       are almost always more than enough to carry out any
 *                       search required and is usually much easier to use than
 *                       some complex regular expressions. If endorseWildcards
 *                       is true then upper or lower letter case is ignored as
 *                       well.
 *
 *                       If you provide a true of false to this parameter then
 *                       you must provide a value (or null) to the option
 *                       <b>byColumnNumber</b> parameter.
* / publi c stati c void filterTable (таблица JTable, параметры String searchCriteria, Object ...)) {int column = -1 ; логическое endorseWildcards = true; if (options.length> 0) {if (options [0]! = null) {column = (int) options [0] - 1; } if (options.length> = 2) {if (options [1]! = null) {endorseWildcards = (логическое) options [1]; }}} Строковые критерии = searchCriteria; if (endorseWildcards) {crit = "(? i)" + searchCriteria.replace ("?", ".?"). replace ("*", ". *?"); } try {TableRowSorter sorter = new TableRowSorter <> (((DefaultTableModel) table.getModel ())); sorter.setRowFilter (столбец <0? RowFilter.regexFilter (критерии): RowFilter.regexFilter (критерии, столбец)); table.setRowSorter (сортировщик); } catch (Exception ex) {ex.printStackTrace (); }} </code>
0 голосов
/ 22 февраля 2020

После изучения и попытки понять asp, как работает класс RowFilter, я, кажется, получил свой стол, чтобы отсортировать его так, как я хочу. Мне все еще нужно провести дополнительное тестирование, но похоже, что оно работает. Я до сих пор не в полной мере gr asp класс RowFilter, поэтому я хотел бы получить некоторые отзывы.

Вот мой код: где ArrayList<Integer> filteredRows = new ArrayList<>(); содержит номера строк, которые я хочу показать. Насколько я понимаю, фильтр автоматически выполняет итерации по моей табличной модели, а идентификатор - это номер строки, которую фильтр обрабатывает в настоящее время. Итак, на первый взгляд, если идентификатор равен любому из номеров строк, которые я сохранил, то покажите его.

RowFilter<DefaultTableModel,Integer> rf = new RowFilter<>() {

    @Override
    public boolean include(Entry<? extends DefaultTableModel, ? extends Integer> entry) {
        int entryRow = entry.getIdentifier();
        for (Integer i : filteredRows) {
            if (entryRow == i) return true;
        }
        return false;
    }

};
TableRowSorter<DefaultTableModel> sorter =  new TableRowSorter<DefaultTableModel>(myTableModel);
sorter.setRowFilter(null);
sorter.setRowFilter(rf);
table.setRowSorter(sorter);
...