|
-
June 22nd, 2005, 02:50 PM
#1
JTables
Hi everyone,
I am currently trying to print a multipage JTable but the the thing is on the left hand side of the JTable does not have any grid lines and i have tried to draw a rectangle around the jTable before printing it but nothing is happening.
Another thing is that when the JTable goes on the next page for printing there are trailing grid lines on the previous page. I have tried clipping and translating it but nothing works.
You guys can try removing the painting of the Table Headers to get a clearer picture if you want
Here is the code with a mini test program so you guys can run the program and see what i mean
Code:
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import java.util.*;
import java.awt.print.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
import javax.imageio.*;
public class JTables2 implements ActionListener
{
JFrame fr = new JFrame ("Frame");
JButton Button12 = new JButton("Print");
DefaultTableModel TableModel1 = new DefaultTableModel(20, 30);
//The below command line sets the table model to the JTable
JTable Table1 = new JTable(TableModel1);
JScrollPane ScrollPane1 = new JScrollPane(Table1, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
Dimension Size1 = new Dimension();
PrinterJob prnJob;
PageFormat format;
public void initialize ()
{
Container pane = fr.getContentPane();
pane.setLayout(new FlowLayout());
fr.setSize(250,300);
fr.setLocation(300,300);
fr.setBackground(Color.lightGray);
//The below command line must be set to false so that user
//resizing is allowed
Table1.setAutoCreateColumnsFromModel(false);
Size1.width = 350;
Size1.height = 250;
ScrollPane1.setPreferredSize(Size1);
Table1.setModel(TableModel1);
Table1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
Table1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
pane.add(ScrollPane1);
pane.add(Button12);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Button12.addActionListener(this);
fr.pack();
fr.setVisible(true);
}
public void printData ()
{
//This function prints the contents of the JTable
StyledTextTableRenderer2 StyledTextTableRenderer1 = new StyledTextTableRenderer2();
StyledTextTableRenderer1.settable(Table1);
try
{
//The below command line gets the printer job
prnJob = PrinterJob.getPrinterJob();
if(format == null)
{
format = prnJob.defaultPage();
}
//The below command line sets the printable interface and the
//format for the page to be printed
prnJob.setPrintable(StyledTextTableRenderer1, format);
//The below command line calls the native print dialog
if(prnJob.printDialog() == false)
{
return;
}
//The below command line prints out the document if the user clicked Ok
prnJob.print();
}
catch (PrinterException e)
{
}
}
public void actionPerformed(ActionEvent event)
{
JComponent b = (JComponent)event.getSource();
if(b == Button12)
{
printData();
fr.repaint();
}
}
public static void main(String args[])
{
JTables2 a = new JTables2();
a.initialize();
}
}
class StyledTextTableRenderer2 implements Printable
{
JTable Table1 = new JTable();
public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException
{
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.black);
int fontHeight = g2.getFontMetrics().getHeight();
int fontDesent = g2.getFontMetrics().getDescent();
//leave room for page number
double pageHeight = pageFormat.getImageableHeight() - fontHeight;
double pageWidth = pageFormat.getImageableWidth();
double tableWidth = (double)Table1.getColumnModel().getTotalColumnWidth();
double headerHeightOnPage = Table1.getTableHeader().getHeight();
double tableWidthOnPage = tableWidth;
double oneRowHeight = (Table1.getRowHeight()+ Table1.getRowMargin());
int numRowsOnAPage = (int)((pageHeight-headerHeightOnPage)/ oneRowHeight);
double pageHeightForTable = oneRowHeight * numRowsOnAPage;
int totalNumPages= (int)Math.ceil(((double)Table1.getRowCount())/numRowsOnAPage);
if(pageIndex>=totalNumPages)
{
Table1.setShowGrid(true);
return NO_SUCH_PAGE;
}
g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
//bottom center
g2.drawString("Page "+ (pageIndex+1), (int)pageWidth/2-35, (int)(pageHeight
+ fontHeight-fontDesent));
g2.translate(0f,headerHeightOnPage);
g2.translate(0f,-pageIndex * pageHeightForTable);
//If this piece of the table is smaller
//than the size available,
//clip to the appropriate bounds.
if(pageIndex + 1 == totalNumPages)
{
int lastRowPrinted = numRowsOnAPage * pageIndex;
int numRowsLeft = Table1.getRowCount() - lastRowPrinted;
g2.setClip(0,(int)(pageHeightForTable * pageIndex), (int) Math.ceil(tableWidthOnPage),
(int)Math.ceil(oneRowHeight * numRowsLeft));
}
//else clip to the entire area available
else
{
g2.setClip(0, (int)(pageHeightForTable*pageIndex), (int) Math.ceil(tableWidthOnPage),
(int) Math.ceil(pageHeightForTable));
}
//This is where i try to draw the rectangle around
//the JTable
g2.drawRect(0,(int)headerHeightOnPage,(int)tableWidthOnPage, (int)((pageHeightForTable)* Table1.getRowCount()));
Table1.paint(g2);
g2.translate(0f, pageIndex * pageHeightForTable);
g2.translate(0f, -headerHeightOnPage);
g2.setClip(0, 0, (int)Math.ceil(tableWidthOnPage),(int)Math.ceil(headerHeightOnPage));
Table1.getTableHeader().paint(g2);
//paint header at top
/*
g2.translate(0f, pageIndex * pageHeightForTable);
g2.setColor(Color.gray);
g2.drawRect(0,0,(int)tableWidthOnPage, (int)((pageHeightForTable)* Table1.getRowCount()));
*/
System.out.println("" + pageHeightForTable);
return Printable.PAGE_EXISTS;
}
public void settable(JTable table)
{
//This function gets the JTable and its table model
Table1 = table;
Table1.setShowGrid(false);
}
}
Basically i am trying to print a JTable with the option of table headers as a complete grid and withou any trainling lines
I know that 1.5 now has printing but i need to use this way of printing(i.e. by using the printable interface) for the program to suit a special kind of need
Any help is greatly appreciated
Thank You
Yous Sincerely
Richard West
-
June 27th, 2005, 12:25 AM
#2
Re: JTables
Try out this piece of coding :
Code:
import javax.swing.*;
import javax.swing.table.*;
import java.awt.print.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.Dimension;
public class Report implements Printable{
JFrame frame;
JTable tableView;
public Report() {
frame = new JFrame("Sales Report");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {System.exit(0);}});
final String[] headers = {"Description", "open price",
"latest price", "End Date", "Quantity"};
final Object[][] data = {
{"Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
{"Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
{"legal pad", "1.00", "2.49", new Date(), new Integer(1)},
{"tape", "1.00", "1.49", new Date(), new Integer(1)},
{"stapler", "4.00", "4.49", new Date(), new Integer(1)},
{"legal pad", "1.00", "2.29", new Date(), new Integer(5)}
};
TableModel dataModel = new AbstractTableModel() {
public int getColumnCount() { return headers.length; }
public int getRowCount() { return data.length;}
public Object getValueAt(int row, int col) {
return data[row][col];}
public String getColumnName(int column) {
return headers[column];}
public Class getColumnClass(int col) {
return getValueAt(0,col).getClass();}
public boolean isCellEditable(int row, int col) {
return (col==1);}
public void setValueAt(Object aValue, int row, int column) {
data[row][column] = aValue;
}
};
tableView = new JTable(dataModel);
JScrollPane scrollpane = new JScrollPane(tableView);
scrollpane.setPreferredSize(new Dimension(500, 80));
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(BorderLayout.CENTER,scrollpane);
frame.pack();
JButton printButton= new JButton();
printButton.setText("print me!");
frame.getContentPane().add(BorderLayout.SOUTH,printButton);
// for faster printing turn double buffering off
RepaintManager.currentManager(
frame).setDoubleBufferingEnabled(false);
printButton.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent evt) {
PrinterJob pj=PrinterJob.getPrinterJob();
pj.setPrintable(Report.this);
pj.printDialog();
try{
pj.print();
}catch (Exception PrintException) {}
}
});
frame.setVisible(true);
}
public int print(Graphics g, PageFormat pageFormat,
int pageIndex) throws PrinterException {
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.black);
int fontHeight=g2.getFontMetrics().getHeight();
int fontDesent=g2.getFontMetrics().getDescent();
//leave room for page number
double pageHeight = pageFormat.getImageableHeight()-fontHeight;
double pageWidth = pageFormat.getImageableWidth();
double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
double scale = 1;
if (tableWidth >= pageWidth) {
scale = pageWidth / tableWidth;
}
double headerHeightOnPage=
tableView.getTableHeader().getHeight()*scale;
double tableWidthOnPage=tableWidth*scale;
double oneRowHeight=(tableView.getRowHeight()+
tableView.getRowMargin())*scale;
int numRowsOnAPage=
(int)((pageHeight-headerHeightOnPage)/oneRowHeight);
double pageHeightForTable=oneRowHeight*numRowsOnAPage;
int totalNumPages= (int)Math.ceil((
(double)tableView.getRowCount())/numRowsOnAPage);
if(pageIndex>=totalNumPages) {
return NO_SUCH_PAGE;
}
g2.translate(pageFormat.getImageableX(),
pageFormat.getImageableY());
g2.drawString("Page: "+(pageIndex+1),(int)pageWidth/2-35,
(int)(pageHeight+fontHeight-fontDesent));//bottom center
g2.translate(0f,headerHeightOnPage);
g2.translate(0f,-pageIndex*pageHeightForTable);
//If this piece of the table is smaller than the size available,
//clip to the appropriate bounds.
if (pageIndex + 1 == totalNumPages) {
int lastRowPrinted = numRowsOnAPage * pageIndex;
int numRowsLeft = tableView.getRowCount() - lastRowPrinted;
g2.setClip(0, (int)(pageHeightForTable * pageIndex),
(int) Math.ceil(tableWidthOnPage),
(int) Math.ceil(oneRowHeight * numRowsLeft));
}
//else clip to the entire area available.
else{
g2.setClip(0, (int)(pageHeightForTable*pageIndex),
(int) Math.ceil(tableWidthOnPage),
(int) Math.ceil(pageHeightForTable));
}
g2.scale(scale,scale);
tableView.paint(g2);
g2.scale(1/scale,1/scale);
g2.translate(0f,pageIndex*pageHeightForTable);
g2.translate(0f, -headerHeightOnPage);
g2.setClip(0, 0,(int) Math.ceil(tableWidthOnPage),
(int)Math.ceil(headerHeightOnPage));
g2.scale(scale,scale);
tableView.getTableHeader().paint(g2);//paint header at top
return Printable.PAGE_EXISTS;
}
public static void main(String[] args) {
new Report();
}
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|