I'm trying to print a JTable (in a JScrollPane in a JFrame) which has 8 rows and a header. I can fit 5 rows on the first page but the second page only will display the 6th row and a little of the 7th and none of the 8th. It appears to me that this is exactly what is showing on the screen and that is exactly what prints and no more. I can't seem to get the whole thing! I've found that if I set the viewport of the scroll pane smaller, that's all that prints, so I'm printing the viewport. I've set the getScrollableTracksViewportHeight to true, but this doesn't work. I appear to have the entire table without the vertical scroll bar, but the off-screen part still doesn't print. The viewport size is 690 x 1000 which should be generous, since the table is only 720 pixels high. I'm printing the JScrollPane rather than the frame but both produce the same. Both pages share the same PageFormat.
This is an inner class.
class PrintTable extends JTable implements Printable, Pageable{
PageFormat pf;
int clipHeight;
int tableHeight;
JScrollPane jsp;
PrintTable(TableModel tm,PageFormat pf){
super(tm);
this.pf = pf;
setDefaultRenderer(JTextArea.class,new TextRenderer()); //renderer is JTextArea
setPreferredScrollableViewportSize(new Dimension(690,1000));
TableColumnModel defaultTCM = getColumnModel();
for (int i=0; i<3; i++) defaultTCM.getColumn(i).setPreferredWidth(100);
setRowHeight(90);
populateTable(SAName); //this gets data into the table from the db
frame = new JFrame();
JViewport jvp = new JViewport();
jvp.setView(new RowNumberHeader(this));
jsp = new JScrollPane(this);
jsp.setRowHeader(jvp);
frame.setContentPane(jsp);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){ }
});
frame.setVisible(true);
frame.pack();
}
public int print(Graphics g, PageFormat pf, int index){
Rectangle clipRect = new Rectangle(0,0,0,0);
Graphics2D g2d = (Graphics2D)g;
JTableHeader head = getTableHeader();
int xCoord = (int)pf.getImageableX();
int yCoord = (int)pf.getImageableY();
int width = (int)pf.getImageableWidth();
int lastRow = rowAtPoint(new Point(xCoord,yCoord+500));
Rectangle rect = getCellRect(lastRow-1,0,true); //the bounds of the last fully visible cell.
clipHeight = rect.y+rect.height+head.getHeight();
g2d.clipRect(xCoord,yCoord,width,clipHeight);
g2d.translate(xCoord,yCoord); //moves the image onto the page's imageable area
int pixelIndex = index*clipHeight;
if (pixelIndex<getHeight()) {
g2d.translate(0,-pixelIndex);
System.out.println("PrintTable.print>pixelIndex= "+pixelIndex);
jsp.paint(g2d);
return Printable.PAGE_EXISTS;
}
return Printable.NO_SUCH_PAGE;
}
public Printable getPrintable(int index){
return this;
}
public PageFormat getPageFormat(int index){
return pf;
}
public int getNumberOfPages(){
return 2;
}
public boolean getScrollableTracksViewportHeight(){
return false;
}
}
I'm running out of paper and patience!
Roy from Iowa