Java JTable过滤数据

时间:2014-08-26 10:02:18

标签: java swing jtable keylistener rowfilter

我无法正确地将过滤器应用于JTable。

private static TableRowSorter<SQLiteTableModel> sorter = null;
...
private void jTFSearchOtherKeyPressed(java.awt.event.KeyEvent evt) {                                          

    jTableOther.setRowSorter(sorter);
    String text3 = jTFSearchOther.getText();
    if (text3.length() == 0) {
        sorter.setRowFilter(null);
    } else {
        sorter.setRowFilter(RowFilter.regexFilter(text3));
    }
} 

一个表已排序,另一个表发生错误

 private void jTFSearchOtherKeyPressed(java.awt.event.KeyEvent evt) {                                          
        jTableOther.setRowSorter(sorter);
        String text3 = jTFSearchOther.getText();
        if (text3.length() == 0) {
            sorter.setRowFilter(null);
        } else {
            sorter.setRowFilter(RowFilter.regexFilter(text3));
        }
    }  

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 4
    at testovoezadanie.demo.SQLiteTableModel.getValueAt(SQLiteTableModel.java:137)
    at javax.swing.JTable.getValueAt(JTable.java:2719)
    at javax.swing.JTable.prepareRenderer(JTable.java:5720)
    at javax.swing.plaf.basic.BasicTableUI.paintCell(BasicTableUI.java:2114)
    at javax.swing.plaf.basic.BasicTableUI.paintCells(BasicTableUI.java:2016)
    at javax.swing.plaf.basic.BasicTableUI.paint(BasicTableUI.java:1812)
    at javax.swing.plaf.ComponentUI.update(ComponentUI.java:161)
    at javax.swing.JComponent.paintComponent(JComponent.java:777)
    at javax.swing.JComponent.paint(JComponent.java:1053)
    at javax.swing.JComponent.paintChildren(JComponent.java:886)

第137行

@Override
    public Object getValueAt(int row, int column) {
        return contents[row][column];
    }

2 个答案:

答案 0 :(得分:0)

内容数组可能有其他参考,然后模型在应用过滤器时询问, 所以试试这个

public Object getValueAt(int row, int column) {

        if(contents.length>row && contents[row].length>column)
        return contents[row][column];
        return null;//must solve this issue when object not found
    }

答案 1 :(得分:0)

这里进行过滤

    private void updateTableManager() throws SQLException {

    SQLiteTableModel modelManager;

    modelManager = new SQLiteTableModel(connectDB, "VIEW_MANAGER");

    jTableManager.setModel(modelManager);

    sorter = new TableRowSorter<>(modelManager);

    sorter.setComparator(2, new SQLiteComparator());

    jTableManager.setRowSorter(sorter);
}

这里没有

    private void updateTableWorker() throws SQLException {

    SQLiteTableModel modelWorker;

    modelWorker = new SQLiteTableModel(connectDB, "VIEW_MANAGER_WORKER");

    jTableManagerWorker.setModel(modelWorker);

    sorter = new TableRowSorter<>(modelWorker);

    sorter.setComparator(2, new SQLiteComparator());

    jTableManagerWorker.setRowSorter(sorter);
}