I am able to print a full JTable, but actually I would like more to print just a specific part of a JTable, for example from Row 10 to Row 50 and Column 70 to Column 150. How to do it ?
Asked
Active
Viewed 2,453 times
1
-
4Possibly using a [`TableRowSorter`](http://docs.oracle.com/javase/7/docs/api/javax/swing/table/TableRowSorter.html) (which also performs filtering) to limit the rows to those in the range. – Andrew Thompson Feb 21 '13 at 13:15
-
Does this limit the number of rows in the view without modifying the model ? – Olivier CLERO Feb 21 '13 at 13:17
-
1A `TableRowSorter` works only on the view side. It does not affect the underlying `TableModel` – Robin Feb 21 '13 at 13:44
-
Is there anything like this for the columns ? – Olivier CLERO Feb 21 '13 at 13:51
-
`JTable#removeColumn` – Robin Feb 21 '13 at 13:57
2 Answers
2
I've faced this problem too. Solved by hiding columns before printing and restoring columns after printing:
// get column num from settings
int num = gridSettings.getColumnsOnPage();// first <num> columns of the table will be printed
final TableColumnModel model = table.getColumnModel();
// list of removed columns. After printing we add them back
final List<TableColumn> removed = new ArrayList<TableColumn>();
int columnCount = model.getColumnCount();
// hiding columns which are not used for printing
for(int i = num; i < columnCount; ++i){
TableColumn col = model.getColumn(num);
removed.add(col);
model.removeColumn(col);
}
// printing after GUI will be updated
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// table printing
try {
table.print(PrintMode.FIT_WIDTH, null, null, true, hpset, true); // here can be your printing
} catch (PrinterException e) {
e.printStackTrace();
}
// columns restoring
for(TableColumn col : removed){
model.addColumn(col);
}
}
});
For printing your specific part of a JTable, just change a little bit this code.

Iuri Sitinschi
- 21
- 3
-
The best way is just set the column width to zero then it will be hidden:). I've answered here >> https://stackoverflow.com/a/67255138/7420535 – talklesscodemore Apr 25 '21 at 15:36
1
Get cell bounds for the selected fragment and calculate desired region (Rectangle
), define clip region to paint only desired region, in the printable use Graphics's
translate() method to shift the rendering.

StanislavL
- 56,971
- 9
- 68
- 98
-
That's approximately what I did. Using Rectangle solved a big part of the problem, thanks! – Olivier CLERO Jun 13 '13 at 14:47