JTable排序和Jasper报告输出

时间:2011-12-06 06:17:13

标签: java swing jtable jasper-reports

在我的一个基于Java swing桌面的应用程序中,我使用的是JTable,我为列添加了排序功能。我需要根据用户添加的数值对其进行排序,然后获取jasper报告输出。

目前,在排序并打印报告后,报告未显示已排序的订单。但是当从DB获取值时的顺序。如何打印用户表格排序顺序的报告?

这是我的jasper报告生成代码

try {
    DefaultTableModel de = (DefaultTableModel)Dashboard.catalogTbl.getModel();
    JRTableModelDataSource jr = new JRTableModelDataSource(de);
    String reportName = reportPath + "reports/AuctionSale/Catalogue/catalouge_frm_tbl.jrxml";
    String compiledName = reportPath + "reports/AuctionSale/Catalogue/catalouge_frm_tbl.jasper";
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("Lot_No", "Lot No");
    params.put("Mark", "Mark");
    params.put("Invoice", "Invoice");
    params.put("Grade", "Grade");
    params.put("Weight", "Weight");
    params.put("Price", "Price");
    params.put("Buyer", "Buyer");
    JasperCompileManager.compileReportToFile(reportName, compiledName);
    JasperPrint jasperPrint = JasperFillManager.fillReport(compiledName, params, jr);
    JasperViewer.viewReport(jasperPrint, false);
} catch (Exception e) {
    e.printStackTrace();
}

3 个答案:

答案 0 :(得分:2)

我想报告是根据TableModel生成的,而典型的排序只会影响JTable本身,而不会影响模型。

您可以做的是装饰您传递给报告生成器的表格模型,以便它接管JTable的排序。

风格的东西
public class TableModelDecorator implements TableModel{
  private TableModel delegate;
  private JTable table;

  @Override
  public Object getValueAt( int rowIndex, int columnIndex ) {
    return delegate.getValueAt( table.convertRowIndexToView( rowIndex ), table.convertColumnIndexToView( columnIndex ) );
  }
}

然后是所有相关方法。

答案 1 :(得分:2)

@Robin答案基本上是正确的,只是转换为jasper发言:-)

“decorator”是JRDataSource或(此处)JRRewindableDataSource的自定义实现。使它成为仅数据并基于表的RowSorter,类似于(谨防:刚刚编译,未经过测试!)

public class JRTableSorterDataSource implements JRRewindableDataSource {

    private RowSorter<? extends TableModel> sorter;

    private int currentRow = -1;

    private HashMap<String, Integer> columnNames = new HashMap<String, Integer>();

    public JRTableSorterDataSource(RowSorter<? extends TableModel> sorter) {
        if (sorter == null) return; // do nothing, no sorter
        this.sorter = sorter;
        TableModel tableModel = sorter.getModel();
        if (tableModel != null) {
            for (int i = 0; i < tableModel.getColumnCount(); i++) {
                this.columnNames.put(tableModel.getColumnName(i),
                        Integer.valueOf(i));
            }
        }

    }

    @Override
    public Object getFieldValue(JRField field) throws JRException {
        String fieldName = field.getName();
        Integer columnIndex = this.columnNames.get(fieldName);
        return sorter.getModel().getValueAt(sorter.convertRowIndexToModel(currentRow), columnIndex.intValue());
    }


    @Override
    public boolean next() throws JRException {
        if (sorter == null || sorter.getModel() == null)
            return false;
        this.currentRow++;
        return (this.currentRow < sorter.getViewRowCount());
    }

    @Override
    public void moveFirst() throws JRException {
        this.currentRow = -1;
    }

    protected int getColumnIndex(JRField field) throws JRException {
        String fieldName = field.getName();
        Integer columnIndex = this.columnNames.get(fieldName);

        if (columnIndex != null) {
            return columnIndex;
        } else if (fieldName.startsWith("COLUMN_")) {
            return Integer.parseInt(fieldName.substring(7));
        }
        throw new JRException("Unknown column name : " + fieldName);
    }

}

然后在设置报告时使用它:

JRDataSource jr = new JRTableSorterDataSource(Dashboard.catalogTbl.getRowSorter());
/// ... same as your example

修改

只是一个非常快速的可运行代码段(懒得做一个完整的报告,忘记这些文件是如何工作的;-) - 所以我们在这里创建一个表(使用标准的SwingX模型),在其RowSorter上创建一个dataSource并循环第一列的值,没问题:

    JTable table = new JXTable(new AncientSwingTeam());
    JRDataSource source = new JRTableSorterDataSource(table.getRowSorter());
    table.getRowSorter().toggleSortOrder(0);
    JRField field = createField("First Name");
    String firstNames = "First Name: ";
    while (source.next()) {
        firstNames += "\n  " + source.getFieldValue(field);
    }
    LOG.info(firstNames);

答案 2 :(得分:0)

有些晚了,但我希望它可以帮助某人:

在这段代码中,我要做的是将过滤器应用于jTable1之后,将获得的行放置在辅助模型中。

然后我将辅助模型分配给辅助表。该表就是我将发送给JasperReports的表。

//** jTable1 is the table in the jFrame where the data is loaded and I apply
//the RowFilter or RowSorter filters

    DefaultTableModel dataModel_tableFiltered = null; //auxiliary model
    JTable tableAuxiliary = null; //table where we will put the auxiliary model

    public constructor {
            
        dataModel_tableFiltered = new DefaultTableModel ();
        // Set the number and name of the columns in the auxiliary model
        for (int i = 0; i <jTable1.getColumnCount(); i ++) {
            dataModel_tableFiltered.addColumn(jTable1.getColumnName (i));
        }
        
        tableAuxiliary = new JTable ();
    }



    private void btn_PrintActionPerformed (java.awt.event.ActionEvent evt) {

        fillModel_filtered ();

        try {
            Map params = new HashMap ();
            params.put ("nameCustomer", "**");

            JRDataSource dataSource = new JRTableModelDataSource (tableAuxiliary.getModel ());
            JasperPrint print = JasperFillManager.fillReport (reportPath, params, dataSource);
            JasperViewer.viewReport (print, false); // true == Exit on Close
        } catch (JRException ex) {
            ex.printStackTrace ();
        }

     }

    // Put resulting rows in the model after applying filters in jTable1
    public void fillModel_filtered () {
        dataModel_tableFiltered.setRowCount (0); // Empty rows of the model

        for (int i = 0; i <jTable1.getRowCount (); i ++) {
            Object row [] = new Object [jTable1.getColumnCount ()];
            for (int j = 0; j <jTable1.getColumnCount (); j ++) {
                row [j] = jTable1.getValueAt (i, j);
            }
            dataModel_tableFiltered.addRow (row);
        }
        tableAuxiliary.setModel(dataModel_tableFiltered); // Very Important
    }