2010-04-24 35 views
1

我有一個應用程序,我想打印一個JTable,但由於它有很多列,我希望用戶選擇/限制要打印的列,以便它可以放入常規打印機紙張。從JTable打印用戶指定的列

我正在使用JTable.print()函數來打印。 (http://java.sun.com/docs/books/tutorial/uiswing/misc/printtable.html) 現在,我的解決方案是用用戶選擇的列創建另一個JTable,然後用數據重新填充表,然後將其發送到打印機。

有沒有更好的方法來做到這一點?

+2

這樣做的好處是,用戶可以準確地看到要打印的內容,就像打印預覽一樣。 – 2010-04-24 18:08:00

回答

0

正如我已經回答了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中的特定部分,只改變一點點這個代碼。