JTable sorting and Jasper report output












2














In my one of Java swing desktop based applications, I am using a JTable and I added the sorting functionality for a column. I need to sort it according to the number values added by the user and then get the jasper report output.



Currently after the sorting and print the report, the report is not showing the sorted order. But the order when the values taken from the DB. How can I print the report which the user's table sorting order?



This is my jasper report generating code



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();
}









share|improve this question
























  • You might want to look more closely at the tag selections in future. I bet that jasper is not what you thought it was. ;) BTW What Have You Tried?
    – Andrew Thompson
    Dec 6 '11 at 6:33












  • @Mujahid what's, where's your problem exactly, because JasperReports and Java API are by different vendors,
    – mKorbel
    Dec 6 '11 at 7:37










  • @AndrewThompson I added the report generating code here. Please can you check it again? Thanks
    – Mujahid
    Dec 6 '11 at 7:55
















2














In my one of Java swing desktop based applications, I am using a JTable and I added the sorting functionality for a column. I need to sort it according to the number values added by the user and then get the jasper report output.



Currently after the sorting and print the report, the report is not showing the sorted order. But the order when the values taken from the DB. How can I print the report which the user's table sorting order?



This is my jasper report generating code



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();
}









share|improve this question
























  • You might want to look more closely at the tag selections in future. I bet that jasper is not what you thought it was. ;) BTW What Have You Tried?
    – Andrew Thompson
    Dec 6 '11 at 6:33












  • @Mujahid what's, where's your problem exactly, because JasperReports and Java API are by different vendors,
    – mKorbel
    Dec 6 '11 at 7:37










  • @AndrewThompson I added the report generating code here. Please can you check it again? Thanks
    – Mujahid
    Dec 6 '11 at 7:55














2












2








2


4





In my one of Java swing desktop based applications, I am using a JTable and I added the sorting functionality for a column. I need to sort it according to the number values added by the user and then get the jasper report output.



Currently after the sorting and print the report, the report is not showing the sorted order. But the order when the values taken from the DB. How can I print the report which the user's table sorting order?



This is my jasper report generating code



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();
}









share|improve this question















In my one of Java swing desktop based applications, I am using a JTable and I added the sorting functionality for a column. I need to sort it according to the number values added by the user and then get the jasper report output.



Currently after the sorting and print the report, the report is not showing the sorted order. But the order when the values taken from the DB. How can I print the report which the user's table sorting order?



This is my jasper report generating code



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();
}






java swing jtable jasper-reports






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 7 '11 at 9:51









kleopatra

44.6k1673159




44.6k1673159










asked Dec 6 '11 at 6:17









MujahidMujahid

69852453




69852453












  • You might want to look more closely at the tag selections in future. I bet that jasper is not what you thought it was. ;) BTW What Have You Tried?
    – Andrew Thompson
    Dec 6 '11 at 6:33












  • @Mujahid what's, where's your problem exactly, because JasperReports and Java API are by different vendors,
    – mKorbel
    Dec 6 '11 at 7:37










  • @AndrewThompson I added the report generating code here. Please can you check it again? Thanks
    – Mujahid
    Dec 6 '11 at 7:55


















  • You might want to look more closely at the tag selections in future. I bet that jasper is not what you thought it was. ;) BTW What Have You Tried?
    – Andrew Thompson
    Dec 6 '11 at 6:33












  • @Mujahid what's, where's your problem exactly, because JasperReports and Java API are by different vendors,
    – mKorbel
    Dec 6 '11 at 7:37










  • @AndrewThompson I added the report generating code here. Please can you check it again? Thanks
    – Mujahid
    Dec 6 '11 at 7:55
















You might want to look more closely at the tag selections in future. I bet that jasper is not what you thought it was. ;) BTW What Have You Tried?
– Andrew Thompson
Dec 6 '11 at 6:33






You might want to look more closely at the tag selections in future. I bet that jasper is not what you thought it was. ;) BTW What Have You Tried?
– Andrew Thompson
Dec 6 '11 at 6:33














@Mujahid what's, where's your problem exactly, because JasperReports and Java API are by different vendors,
– mKorbel
Dec 6 '11 at 7:37




@Mujahid what's, where's your problem exactly, because JasperReports and Java API are by different vendors,
– mKorbel
Dec 6 '11 at 7:37












@AndrewThompson I added the report generating code here. Please can you check it again? Thanks
– Mujahid
Dec 6 '11 at 7:55




@AndrewThompson I added the report generating code here. Please can you check it again? Thanks
– Mujahid
Dec 6 '11 at 7:55












3 Answers
3






active

oldest

votes


















2














I guess the report is generated based on the TableModel, while typical sorting only affect the JTable itself, not the model.



What you could do is decorate the table model which you pass to your report generator so that it takes over the ordering of your JTable. Something in the style of



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 ) );
}
}


but then for all relevant methods.






share|improve this answer



















  • 1




    Guesses and suggestions to provide more information are moving close to 'comment' territory.
    – Andrew Thompson
    Dec 6 '11 at 6:43










  • Slightly off-topic: I am quite new here. Are there any guidelines when to use comments and when to use actual answers ? I did not encounter such section in the FAQ
    – Robin
    Dec 6 '11 at 6:50






  • 1




    I'm not sure of any references for you, just past experience. I'm also not sure whether it should be an answer or comment. From my experience, it seems border-line either way.
    – Andrew Thompson
    Dec 6 '11 at 6:54










  • Hi Robin, Please check the question again. I added the code tht I used to generate the report Thanks
    – Mujahid
    Dec 6 '11 at 7:54










  • Like I thought, you just pass the table model, which is unaware of any sorting that is applied
    – Robin
    Dec 6 '11 at 8:55



















2














@Robin answer is basically correct, just translating to jasper speak :-)



The "decorator" is a custom implementation of JRDataSource or (here) JRRewindableDataSource. Make it data-only and base on the table's RowSorter, something like (beware: just compiled, not tested!)



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);
}

}


Then use it when setting up your report:



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


Edit



just a very quick runnable snippet (too lazy to do a full report, forgot how those files work ;-) - so here we create a table (with a standard SwingX model), create a dataSource on its RowSorter and loop over the values of the first column, no problem:



    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);





share|improve this answer























  • Thanks a lot. I run that code and I'm getting that following exception: java.lang.NullPointerException at action.JRTableSorterDataSource.getFieldValue(JRTableSorterDataSource.java:43)
    – Mujahid
    Dec 6 '11 at 12:16










  • Thanks. I don't speak Jasper, only Java and a bit of Swing ;-)
    – Robin
    Dec 6 '11 at 12:17










  • @Mujahid well, as I said, didn't run - probably missed a guard against null somewhere. And as you know, this forum is about helping, not about doing all the work - simply track it down :-)
    – kleopatra
    Dec 6 '11 at 12:30










  • @kleopatra: Thanks a lot. I'll try them. Thanks
    – Mujahid
    Dec 7 '11 at 11:17



















0














Something late, but I hope it helps someone:



In this code, what I do is that after applying the filters in the jTable1, place the rows obtained in the auxiliary model.



Then I assigned the auxiliary model to the auxiliary table. And that table is the one I'll send to 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
}





share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f8396078%2fjtable-sorting-and-jasper-report-output%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2














    I guess the report is generated based on the TableModel, while typical sorting only affect the JTable itself, not the model.



    What you could do is decorate the table model which you pass to your report generator so that it takes over the ordering of your JTable. Something in the style of



    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 ) );
    }
    }


    but then for all relevant methods.






    share|improve this answer



















    • 1




      Guesses and suggestions to provide more information are moving close to 'comment' territory.
      – Andrew Thompson
      Dec 6 '11 at 6:43










    • Slightly off-topic: I am quite new here. Are there any guidelines when to use comments and when to use actual answers ? I did not encounter such section in the FAQ
      – Robin
      Dec 6 '11 at 6:50






    • 1




      I'm not sure of any references for you, just past experience. I'm also not sure whether it should be an answer or comment. From my experience, it seems border-line either way.
      – Andrew Thompson
      Dec 6 '11 at 6:54










    • Hi Robin, Please check the question again. I added the code tht I used to generate the report Thanks
      – Mujahid
      Dec 6 '11 at 7:54










    • Like I thought, you just pass the table model, which is unaware of any sorting that is applied
      – Robin
      Dec 6 '11 at 8:55
















    2














    I guess the report is generated based on the TableModel, while typical sorting only affect the JTable itself, not the model.



    What you could do is decorate the table model which you pass to your report generator so that it takes over the ordering of your JTable. Something in the style of



    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 ) );
    }
    }


    but then for all relevant methods.






    share|improve this answer



















    • 1




      Guesses and suggestions to provide more information are moving close to 'comment' territory.
      – Andrew Thompson
      Dec 6 '11 at 6:43










    • Slightly off-topic: I am quite new here. Are there any guidelines when to use comments and when to use actual answers ? I did not encounter such section in the FAQ
      – Robin
      Dec 6 '11 at 6:50






    • 1




      I'm not sure of any references for you, just past experience. I'm also not sure whether it should be an answer or comment. From my experience, it seems border-line either way.
      – Andrew Thompson
      Dec 6 '11 at 6:54










    • Hi Robin, Please check the question again. I added the code tht I used to generate the report Thanks
      – Mujahid
      Dec 6 '11 at 7:54










    • Like I thought, you just pass the table model, which is unaware of any sorting that is applied
      – Robin
      Dec 6 '11 at 8:55














    2












    2








    2






    I guess the report is generated based on the TableModel, while typical sorting only affect the JTable itself, not the model.



    What you could do is decorate the table model which you pass to your report generator so that it takes over the ordering of your JTable. Something in the style of



    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 ) );
    }
    }


    but then for all relevant methods.






    share|improve this answer














    I guess the report is generated based on the TableModel, while typical sorting only affect the JTable itself, not the model.



    What you could do is decorate the table model which you pass to your report generator so that it takes over the ordering of your JTable. Something in the style of



    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 ) );
    }
    }


    but then for all relevant methods.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Dec 6 '11 at 10:22

























    answered Dec 6 '11 at 6:40









    RobinRobin

    31.5k43879




    31.5k43879








    • 1




      Guesses and suggestions to provide more information are moving close to 'comment' territory.
      – Andrew Thompson
      Dec 6 '11 at 6:43










    • Slightly off-topic: I am quite new here. Are there any guidelines when to use comments and when to use actual answers ? I did not encounter such section in the FAQ
      – Robin
      Dec 6 '11 at 6:50






    • 1




      I'm not sure of any references for you, just past experience. I'm also not sure whether it should be an answer or comment. From my experience, it seems border-line either way.
      – Andrew Thompson
      Dec 6 '11 at 6:54










    • Hi Robin, Please check the question again. I added the code tht I used to generate the report Thanks
      – Mujahid
      Dec 6 '11 at 7:54










    • Like I thought, you just pass the table model, which is unaware of any sorting that is applied
      – Robin
      Dec 6 '11 at 8:55














    • 1




      Guesses and suggestions to provide more information are moving close to 'comment' territory.
      – Andrew Thompson
      Dec 6 '11 at 6:43










    • Slightly off-topic: I am quite new here. Are there any guidelines when to use comments and when to use actual answers ? I did not encounter such section in the FAQ
      – Robin
      Dec 6 '11 at 6:50






    • 1




      I'm not sure of any references for you, just past experience. I'm also not sure whether it should be an answer or comment. From my experience, it seems border-line either way.
      – Andrew Thompson
      Dec 6 '11 at 6:54










    • Hi Robin, Please check the question again. I added the code tht I used to generate the report Thanks
      – Mujahid
      Dec 6 '11 at 7:54










    • Like I thought, you just pass the table model, which is unaware of any sorting that is applied
      – Robin
      Dec 6 '11 at 8:55








    1




    1




    Guesses and suggestions to provide more information are moving close to 'comment' territory.
    – Andrew Thompson
    Dec 6 '11 at 6:43




    Guesses and suggestions to provide more information are moving close to 'comment' territory.
    – Andrew Thompson
    Dec 6 '11 at 6:43












    Slightly off-topic: I am quite new here. Are there any guidelines when to use comments and when to use actual answers ? I did not encounter such section in the FAQ
    – Robin
    Dec 6 '11 at 6:50




    Slightly off-topic: I am quite new here. Are there any guidelines when to use comments and when to use actual answers ? I did not encounter such section in the FAQ
    – Robin
    Dec 6 '11 at 6:50




    1




    1




    I'm not sure of any references for you, just past experience. I'm also not sure whether it should be an answer or comment. From my experience, it seems border-line either way.
    – Andrew Thompson
    Dec 6 '11 at 6:54




    I'm not sure of any references for you, just past experience. I'm also not sure whether it should be an answer or comment. From my experience, it seems border-line either way.
    – Andrew Thompson
    Dec 6 '11 at 6:54












    Hi Robin, Please check the question again. I added the code tht I used to generate the report Thanks
    – Mujahid
    Dec 6 '11 at 7:54




    Hi Robin, Please check the question again. I added the code tht I used to generate the report Thanks
    – Mujahid
    Dec 6 '11 at 7:54












    Like I thought, you just pass the table model, which is unaware of any sorting that is applied
    – Robin
    Dec 6 '11 at 8:55




    Like I thought, you just pass the table model, which is unaware of any sorting that is applied
    – Robin
    Dec 6 '11 at 8:55













    2














    @Robin answer is basically correct, just translating to jasper speak :-)



    The "decorator" is a custom implementation of JRDataSource or (here) JRRewindableDataSource. Make it data-only and base on the table's RowSorter, something like (beware: just compiled, not tested!)



    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);
    }

    }


    Then use it when setting up your report:



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


    Edit



    just a very quick runnable snippet (too lazy to do a full report, forgot how those files work ;-) - so here we create a table (with a standard SwingX model), create a dataSource on its RowSorter and loop over the values of the first column, no problem:



        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);





    share|improve this answer























    • Thanks a lot. I run that code and I'm getting that following exception: java.lang.NullPointerException at action.JRTableSorterDataSource.getFieldValue(JRTableSorterDataSource.java:43)
      – Mujahid
      Dec 6 '11 at 12:16










    • Thanks. I don't speak Jasper, only Java and a bit of Swing ;-)
      – Robin
      Dec 6 '11 at 12:17










    • @Mujahid well, as I said, didn't run - probably missed a guard against null somewhere. And as you know, this forum is about helping, not about doing all the work - simply track it down :-)
      – kleopatra
      Dec 6 '11 at 12:30










    • @kleopatra: Thanks a lot. I'll try them. Thanks
      – Mujahid
      Dec 7 '11 at 11:17
















    2














    @Robin answer is basically correct, just translating to jasper speak :-)



    The "decorator" is a custom implementation of JRDataSource or (here) JRRewindableDataSource. Make it data-only and base on the table's RowSorter, something like (beware: just compiled, not tested!)



    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);
    }

    }


    Then use it when setting up your report:



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


    Edit



    just a very quick runnable snippet (too lazy to do a full report, forgot how those files work ;-) - so here we create a table (with a standard SwingX model), create a dataSource on its RowSorter and loop over the values of the first column, no problem:



        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);





    share|improve this answer























    • Thanks a lot. I run that code and I'm getting that following exception: java.lang.NullPointerException at action.JRTableSorterDataSource.getFieldValue(JRTableSorterDataSource.java:43)
      – Mujahid
      Dec 6 '11 at 12:16










    • Thanks. I don't speak Jasper, only Java and a bit of Swing ;-)
      – Robin
      Dec 6 '11 at 12:17










    • @Mujahid well, as I said, didn't run - probably missed a guard against null somewhere. And as you know, this forum is about helping, not about doing all the work - simply track it down :-)
      – kleopatra
      Dec 6 '11 at 12:30










    • @kleopatra: Thanks a lot. I'll try them. Thanks
      – Mujahid
      Dec 7 '11 at 11:17














    2












    2








    2






    @Robin answer is basically correct, just translating to jasper speak :-)



    The "decorator" is a custom implementation of JRDataSource or (here) JRRewindableDataSource. Make it data-only and base on the table's RowSorter, something like (beware: just compiled, not tested!)



    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);
    }

    }


    Then use it when setting up your report:



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


    Edit



    just a very quick runnable snippet (too lazy to do a full report, forgot how those files work ;-) - so here we create a table (with a standard SwingX model), create a dataSource on its RowSorter and loop over the values of the first column, no problem:



        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);





    share|improve this answer














    @Robin answer is basically correct, just translating to jasper speak :-)



    The "decorator" is a custom implementation of JRDataSource or (here) JRRewindableDataSource. Make it data-only and base on the table's RowSorter, something like (beware: just compiled, not tested!)



    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);
    }

    }


    Then use it when setting up your report:



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


    Edit



    just a very quick runnable snippet (too lazy to do a full report, forgot how those files work ;-) - so here we create a table (with a standard SwingX model), create a dataSource on its RowSorter and loop over the values of the first column, no problem:



        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);






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Dec 6 '11 at 13:31

























    answered Dec 6 '11 at 11:53









    kleopatrakleopatra

    44.6k1673159




    44.6k1673159












    • Thanks a lot. I run that code and I'm getting that following exception: java.lang.NullPointerException at action.JRTableSorterDataSource.getFieldValue(JRTableSorterDataSource.java:43)
      – Mujahid
      Dec 6 '11 at 12:16










    • Thanks. I don't speak Jasper, only Java and a bit of Swing ;-)
      – Robin
      Dec 6 '11 at 12:17










    • @Mujahid well, as I said, didn't run - probably missed a guard against null somewhere. And as you know, this forum is about helping, not about doing all the work - simply track it down :-)
      – kleopatra
      Dec 6 '11 at 12:30










    • @kleopatra: Thanks a lot. I'll try them. Thanks
      – Mujahid
      Dec 7 '11 at 11:17


















    • Thanks a lot. I run that code and I'm getting that following exception: java.lang.NullPointerException at action.JRTableSorterDataSource.getFieldValue(JRTableSorterDataSource.java:43)
      – Mujahid
      Dec 6 '11 at 12:16










    • Thanks. I don't speak Jasper, only Java and a bit of Swing ;-)
      – Robin
      Dec 6 '11 at 12:17










    • @Mujahid well, as I said, didn't run - probably missed a guard against null somewhere. And as you know, this forum is about helping, not about doing all the work - simply track it down :-)
      – kleopatra
      Dec 6 '11 at 12:30










    • @kleopatra: Thanks a lot. I'll try them. Thanks
      – Mujahid
      Dec 7 '11 at 11:17
















    Thanks a lot. I run that code and I'm getting that following exception: java.lang.NullPointerException at action.JRTableSorterDataSource.getFieldValue(JRTableSorterDataSource.java:43)
    – Mujahid
    Dec 6 '11 at 12:16




    Thanks a lot. I run that code and I'm getting that following exception: java.lang.NullPointerException at action.JRTableSorterDataSource.getFieldValue(JRTableSorterDataSource.java:43)
    – Mujahid
    Dec 6 '11 at 12:16












    Thanks. I don't speak Jasper, only Java and a bit of Swing ;-)
    – Robin
    Dec 6 '11 at 12:17




    Thanks. I don't speak Jasper, only Java and a bit of Swing ;-)
    – Robin
    Dec 6 '11 at 12:17












    @Mujahid well, as I said, didn't run - probably missed a guard against null somewhere. And as you know, this forum is about helping, not about doing all the work - simply track it down :-)
    – kleopatra
    Dec 6 '11 at 12:30




    @Mujahid well, as I said, didn't run - probably missed a guard against null somewhere. And as you know, this forum is about helping, not about doing all the work - simply track it down :-)
    – kleopatra
    Dec 6 '11 at 12:30












    @kleopatra: Thanks a lot. I'll try them. Thanks
    – Mujahid
    Dec 7 '11 at 11:17




    @kleopatra: Thanks a lot. I'll try them. Thanks
    – Mujahid
    Dec 7 '11 at 11:17











    0














    Something late, but I hope it helps someone:



    In this code, what I do is that after applying the filters in the jTable1, place the rows obtained in the auxiliary model.



    Then I assigned the auxiliary model to the auxiliary table. And that table is the one I'll send to 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
    }





    share|improve this answer


























      0














      Something late, but I hope it helps someone:



      In this code, what I do is that after applying the filters in the jTable1, place the rows obtained in the auxiliary model.



      Then I assigned the auxiliary model to the auxiliary table. And that table is the one I'll send to 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
      }





      share|improve this answer
























        0












        0








        0






        Something late, but I hope it helps someone:



        In this code, what I do is that after applying the filters in the jTable1, place the rows obtained in the auxiliary model.



        Then I assigned the auxiliary model to the auxiliary table. And that table is the one I'll send to 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
        }





        share|improve this answer












        Something late, but I hope it helps someone:



        In this code, what I do is that after applying the filters in the jTable1, place the rows obtained in the auxiliary model.



        Then I assigned the auxiliary model to the auxiliary table. And that table is the one I'll send to 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
        }






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 21 '18 at 19:23









        Isaias Cruz E.Isaias Cruz E.

        1




        1






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f8396078%2fjtable-sorting-and-jasper-report-output%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Feedback on college project

            Futebolista

            Albești (Vaslui)