I am trying to find a way to programmatically set page breaks for printing out a JTable.
E.g., I have a table with approx 150 rows like this:
Line Number Data1 Data2 Data3 …etc
1 a b c d
1 a b c d
1 a b c d
2 a b c d
2 a b c d
3 a b c d
3 a b c d
3 a b c d
3 a b c d
4 a b c d
5 a b c d
5 a b c d
5 a b c d
…etc …etc …etc …etc …etc
I need to find a way to start printing a new page when the line number changes.
I found a method for printing selected rows, and so far have modified it to loop through my table adding rows to a temporary print model and then calling print() method to print before resetting the temporary variables. However, this means that I am calling print() maybe 10 times, once for each line number, which is an unacceptable solution. The code that accomplishes current flawed solution is as follows:
btnPrint.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
int wrappingLineNumber = (Integer) table.getValueAt(0, 0);
WrappingSheetsTableModel printModel = new WrappingSheetsTableModel();
for (int i = 0; i < table.getRowCount(); i++) {
if ((Integer)table.getValueAt(i, 0) == wrappingLineNumber) {
System.out.println(table.getValueAt(i, -1));
printModel.addRow((WrappingSheets) table.getValueAt(i, -1));
} else {
wrappingLineNumber = (Integer) table.getValueAt(i, 0);
// if not the same, i.e., value changed
JTable toPrint = new JTable(printModel);
toPrint.setSize(toPrint.getPreferredSize());
JTableHeader tableHeader = toPrint.getTableHeader();
tableHeader.setSize(tableHeader.getPreferredSize());
toPrint.print(JTable.PrintMode.FIT_WIDTH);
printModel.removeAll();
printModel.addRow((WrappingSheets) table.getValueAt(i, -1));
}
}
System.out.println("success printing");
} catch (PrinterException pe) {
System.out.println("printing failed");
pe.printStackTrace();
}
};
});
Can anyone provide a better solution that will start printing on a new page whenever the value in the line number column changes?
Many thanks in advance for any help provided!