How to print out specific rows/columns of a JTable?

徘徊边缘 提交于 2020-01-03 04:23:29

问题


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 ?


回答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.




回答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.



来源:https://stackoverflow.com/questions/15003159/how-to-print-out-specific-rows-columns-of-a-jtable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!