1

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 ?

Michaël
  • 3,679
  • 7
  • 39
  • 64
Olivier CLERO
  • 177
  • 15

2 Answers2

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.

  • 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