我有一个应用程序,我想打印一个 JTable,但由于它有很多列,我希望用户选择/限制要打印的列,以便它可以适合常规打印纸。
我正在使用 JTable.print() 函数进行打印。 (http://java.sun.com/docs/books/tutorial/uiswing/misc/printtable.html) 现在,我的解决方案是使用用户选择的列创建另一个 JTable,然后用数据重新填充表,然后将其发送到打印机。
有更好的方法吗?
最佳答案
正如我所回答的那样here ,我通过在打印之前隐藏列并在打印后恢复列来解决它:
// 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 的特定部分,只需稍微更改此代码即可。
关于java - 从 JTable 打印用户指定的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2705411/