带行Filter的JTable - 如何仅对已过滤的行进行迭代

时间:2015-03-05 13:20:47

标签: java swing jtable tablemodel

我有 JTable ,其中行由 RowFilter 过滤(行B被隐藏)。

如何迭代仅可见行(而不是隐藏的B行)?

不幸的是,下面的示例还打印了 B 行,我想跳过它。

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.RowFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import javax.swing.JButton;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class JTableFilterDemo {
    public static void main(String[] args) {
        Object[][] data = { { "A", 5 }, { "B", 2 }, { "C", 4 }, { "D", 8 } };
        String columnNames[] = { "Item", "Value" };
        TableModel model = new DefaultTableModel(data, columnNames) {
            public Class<?> getColumnClass(int column) {
                return getValueAt(0, column).getClass();
            }
        };
        JTable table = new JTable(model);

        RowFilter<Object, Object> filter = new RowFilter<Object, Object>() {
            public boolean include(Entry entry) {
                Integer population = (Integer) entry.getValue(1);
                return population.intValue() > 3;
            }
        };

        TableRowSorter<TableModel> sorter = new TableRowSorter<TableModel>(
                model);
        sorter.setRowFilter(filter);
        table.setRowSorter(sorter);
        JScrollPane scrollPane = new JScrollPane(table);
        JFrame frame = new JFrame("Filtering Table");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton btnNewButton = new JButton("Print values");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                for(int row = 0;row < table.getModel().getRowCount();row++) {
                        System.out.println(table.getModel().getValueAt(row, 0));
                }
            }
        });
        frame.getContentPane().add(btnNewButton, BorderLayout.SOUTH);
        frame.getContentPane().add(scrollPane);
        frame.setSize(300, 200);
        frame.setVisible(true);
    }
}

1 个答案:

答案 0 :(得分:1)

         for(int row = 0;row < table.getModel().getRowCount();row++) {
                    System.out.println(table.getModel().getValueAt(row, 0));
            }

应替换为:

            for(int row = 0;row < table.getRowCount();row++) {
                System.out.println(table.getModel().getValueAt(table.convertRowIndexToModel(row), 0));
            }