【问题标题】:How to print out specific rows/columns of a JTable?如何打印出 JTable 的特定行/列?
【发布时间】:2014-07-16 19:01:57
【问题描述】:

我可以打印完整的 JTable,但实际上我更希望只打印 JTable 的特定部分,例如从第 10 行到第 50 行以及从第 70 列到第 150 列。 怎么办?

【问题讨论】:

  • 可能使用TableRowSorter(也执行过滤)将行限制在范围内。
  • 这样会限制视图中的行数而不修改模型吗?
  • TableRowSorter 仅在视图侧有效。不影响底层TableModel
  • 列有这样的东西吗?
  • JTable#removeColumn

标签: java swing jtable awt


【解决方案1】:

我也遇到过这个问题。通过在打印前隐藏列并在打印后恢复列来解决:

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

要打印 JTable 的特定部分,只需稍微更改此代码即可。

【讨论】:

【解决方案2】:

获取所选片段的单元格边界并计算所需区域(Rectangle),定义剪辑区域以仅绘制所需区域,在可打印中使用Graphics's translate() 方法来移动渲染。

【讨论】:

  • 这就是我所做的。使用 Rectangle 解决了很大一部分问题,谢谢!
猜你喜欢
  • 2014-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-22
  • 1970-01-01
相关资源
最近更新 更多