Take this code to print JTable, JLael, JPanel in both landscape&portrait m
YOU NEED TWO FILES FOR THIS AND AM GIVING BOTH
1ST FILE WITH MAIN METHOD.
package print;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.border.Border;
public class PrintExample extends JFrame
implements ActionListener {
private String ImageName = "C:\\Documents and Settings\\jbhumana\\Desktop\\academy.gif";
JLabel label;
JTable tableView;
JPanel buttonPanel;
Border tableBorder;
JButton printJPanel = new JButton("Print JPanel");
JButton printJLabel = new JButton("Print JLabel");
JButton printJTable = new JButton("Print JTable");
JRadioButton landscape = new JRadioButton("LandScape");
JRadioButton potrait = new JRadioButton("Potrait");
JPanel radioPanel = new JPanel(new BorderLayout());
ButtonGroup radioGroup = new ButtonGroup();
public PrintExample() {
jbinit();
}
private void jbinit() {
Container content = getContentPane();
printJPanel.addActionListener(this);
printJLabel.addActionListener(this);
printJTable.addActionListener(this);
buttonPanel = new JPanel();
JPanel labelPanel = new JPanel();
label = new JLabel(new ImageIcon(ImageName));
radioPanel.add(landscape, BorderLayout.NORTH);
landscape.setSelected(true);
radioPanel.add(potrait, BorderLayout.SOUTH);
radioPanel.setBackground(Color.LIGHT_GRAY);
radioGroup.add(landscape);
radioGroup.add(potrait);
final String[] headers = {
"SomeText(Descr..)", "Rate(old)",
"Rate(new)", "Date", "Quantity"};
//Table Row declaration
final Object[][] data = {
{
"abc1", "0.10", "7.14", new Date(), new Integer(1)}
, {
"abc2", "2.00", "12.49", new Date(), new Integer(1)}
, {
"abc3", "1.00", "1.49", new Date(), new Integer(9)}
, {
"abc4", "4.00", "14.49", new Date(), new Integer(1)}
, {
"abc5", "6.00", "12.29", new Date(), new Integer(5)}
, {
"abc6", "1.00", "4.99", new Date(), new Integer(2)}
, {
"abc7", "10.10", "20.14", new Date(), new Integer(1)}
, {
"abc8", "1.00", "2.49", new Date(), new Integer(6)}
, {
"abc9", "1.00", "1.49", new Date(), new Integer(1)}
, {
"abc10", "14.00", "34.49", new Date(), new Integer(1)}
, {
"abc11", "61.00", "82.29", new Date(), new Integer(5)}
,
};
// For table data retrival and editing
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;
}
};
//To add table to the scrollpane
tableView = new JTable(dataModel);
JScrollPane scrollpane = new JScrollPane(tableView);
//To add scrollpane to the frame
scrollpane.setPreferredSize(new Dimension(350, 125));
labelPanel.setBackground(Color.LIGHT_GRAY);
labelPanel.add(label);
buttonPanel.add(printJPanel);
buttonPanel.add(printJLabel);
buttonPanel.add(printJTable);
buttonPanel.setBackground(Color.LIGHT_GRAY);
Border tableBorder = BorderFactory.createLineBorder(Color.black);
tableView.setBorder(tableBorder);
content.add(scrollpane, BorderLayout.NORTH);
content.add(labelPanel, BorderLayout.CENTER);
JPanel buttonRadioPanel = new JPanel(new FlowLayout());
buttonRadioPanel.add(radioPanel);
buttonRadioPanel.add(buttonPanel);
buttonRadioPanel.setBackground(Color.LIGHT_GRAY);
content.add(buttonRadioPanel, BorderLayout.SOUTH);
pack();
setSize(500,250);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
if(event.getSource() == this.printJLabel){
PrintUtilities.printComponent(label,"Test header","Test footer",landscape.isSelected()?"landscape":"potrait");
}else if(event.getSource() == this.printJTable){
PrintUtilities.printComponent(tableView,"Test Header","Test Footer",landscape.isSelected()?"landscape":"potrait");
}else if(event.getSource() == this.printJPanel){
PrintUtilities.printComponent(buttonPanel,"Test Header","Test Footer",landscape.isSelected()?"landscape":"potrait");
}
}
public static void main(String[] args) {
PrintExample printExample = new PrintExample();
}
}
**********************************************************************************
2ND FILE WITH PRINTABLE INTERFACE
package print;
import java.awt.*;
import java.awt.print.*;
import javax.swing.*;
import javax.swing.border.Border;
public class PrintUtilities implements Printable {
JTable tableView;
String header="", footer="", pageOrientation="landscape";
private Component printcomponent;
public static void printComponent(Component c, String header, String footer, String pageOrientation) {
new PrintUtilities(c,header,footer,pageOrientation).print();
}
public PrintUtilities(Component printcomponent,String header, String footer, String pageOrientation) {
this.printcomponent = printcomponent;
this.header = header;
this.footer = footer;
this.pageOrientation = pageOrientation;
}
public void print() {
try{
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
if (printJob.printDialog())
try {
printJob.print();
}
catch (PrinterException pe) {
System.out.println("Error in printing: " + pe);
}
}catch(Exception e){
e.printStackTrace();
}
}
public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
try{
if (this.printcomponent instanceof JTable) {
JTable tableView = (JTable)this.printcomponent;
Graphics2D g2 = (Graphics2D) g;
g2.setColor(Color.black);
int fontHeight = g2.getFontMetrics().getHeight()+100;
int fontDesent = g2.getFontMetrics().getDescent();
//for printing footer on a page
if(pageOrientation.equalsIgnoreCase("potrait")){
pageFormat.setOrientation(pageFormat.PORTRAIT);
double pageHeight = pageFormat.getImageableHeight() - fontHeight;
System.out.println("potrait page height....."+pageHeight);
double pageWidth = pageFormat.getImageableWidth();
double tableWidth = (double) tableView.getColumnModel().
getTotalColumnWidth();
double scale = 1;
if (tableWidth >= pageWidth) {
scale = pageWidth / tableWidth;
}
//for setting table header height
double headerHeightOnPage =
(tableView.getTableHeader().getHeight()) * scale;
//for setting table width
double tableWidthOnPage = tableWidth * scale;
//for setting each row height
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);
Border tableBorder = BorderFactory.createLineBorder(Color.black);
tableView.setBorder(tableBorder);
g2.translate(pageFormat.getImageableX()+30,
pageFormat.getImageableY()+10);
//for printing footer on the page
if(footer.trim().length() > 0){
g2.drawString(footer,
(int) pageWidth / 2 - 35,
(int) (pageHeight + fontHeight - fontDesent)-10); //bottom left
}
//for printing header on center of the page
if(header.trim().length() > 0){
int fontWidth = g2.getFontMetrics().stringWidth(header);
g2.drawString(header,
((int) pageWidth / 2) - (int)(fontWidth/2),
-1); //header center
}
g2.translate(0f, headerHeightOnPage+5);
g2.translate(0f, -pageIndex * pageHeightForTable);
//To set the appropriate bounds,
//if the piece of the table is smaller
//than the size available,
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));
}
//or print 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
if (pageIndex >= totalNumPages) {
return NO_SUCH_PAGE;
}
}
else {
pageFormat.setOrientation(pageFormat.LANDSCAPE);
double pageHeight = pageFormat.getImageableHeight() - fontHeight;
System.out.println("landscape page height....."+pageHeight);
double pageWidth = pageFormat.getImageableWidth();
double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
double scale = 1;
if (tableWidth >= pageWidth) {
scale = pageWidth / tableWidth;
}
//for setting table header height
double headerHeightOnPage =
(tableView.getTableHeader().getHeight()) * scale;
//for setting table width
double tableWidthOnPage = tableWidth * scale;
//for setting each row height
double oneRowHeight = (tableView.getRowHeight() +
tableView.getRowMargin() + 1) * scale;
int numRowsOnAPage = (int) ( (pageHeight - headerHeightOnPage) / oneRowHeight);
double pageHeightForTable = oneRowHeight * numRowsOnAPage;
int totalNumPages = (int) Math.ceil( (
(double) tableView.getRowCount()) / numRowsOnAPage);
g2.translate(pageFormat.getImageableX()+20,
pageFormat.getImageableY()+20);
//for printing footer on the page
if(footer.trim().length() > 0){
g2.drawString(footer,
(int) pageWidth / 2 - 35,
(int) (pageHeight + fontHeight - fontDesent)-10); //bottom left
}
//for printing header on center of the page
if(header.trim().length() > 0){
int fontWidth = g2.getFontMetrics().stringWidth(header);
g2.drawString(header,
((int) pageWidth / 2) - (int)(fontWidth/2),
-5); //header center
}
g2.translate(1f, headerHeightOnPage);
g2.translate(1f, -pageIndex * pageHeightForTable);
//To set the appropriate bounds,
//if the piece of the table is smaller
//than the size available,
if (pageIndex + 1 == totalNumPages) {
int lastRowPrinted = numRowsOnAPage * pageIndex;
int numRowsLeft = tableView.getRowCount() - lastRowPrinted;
System.out.println("rows left---------------->"+numRowsLeft);
g2.setClip(0, (int) (pageHeightForTable * pageIndex),
(int) Math.ceil(tableWidthOnPage),
(int) Math.ceil(oneRowHeight * numRowsLeft));
}
//or print 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(1.2f,pageIndex*pageHeightForTable);
g2.translate(1.2f, -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
if (pageIndex >= totalNumPages) {
return NO_SUCH_PAGE;
}
}
return Printable.PAGE_EXISTS;
}
else if(this.printcomponent instanceof JLabel) {
if (pageIndex > 0) {
return (NO_SUCH_PAGE);
}
else {
Graphics2D g2d = (Graphics2D) g;
//printing as per page orientation
if(pageOrientation.equalsIgnoreCase("potrait")){
pageFormat.setOrientation(pageFormat.PORTRAIT);
}else{
pageFormat.setOrientation(pageFormat.LANDSCAPE);
}
g2d.translate(pageFormat.getImageableX()+75,
pageFormat.getImageableY());
int fontWidth = g2d.getFontMetrics().stringWidth(header);
int pageWidth = (int)pageFormat.getImageableWidth();
int pageHeight = (int)pageFormat.getImageableHeight();
System.out.println("pagewidth...."+pageWidth);
System.out.println("printcomponent width..."+printcomponent.getWidth());
int fontHeight = g2d.getFontMetrics().getHeight()+100; //+50
int fontDesent = g2d.getFontMetrics().getDescent();
//setting header in center after traslation/moving
if(header.trim().length() > 0){
g2d.drawString(header,
((int) pageWidth / 2) - (int)(fontWidth/2),
15); //header center
}
if(footer.trim().length() > 0){
g2d.drawString(footer,
((int) pageWidth / 2) - (int)(fontWidth/2),
(int) (pageHeight-15)); //bottom left
}
g2d.translate(pageFormat.getImageableX()+140, pageFormat.getImageableY()+70);
//disableDoubleBuffering(printcomponent);
printcomponent.paint(g2d);
//enableDoubleBuffering(printcomponent);
return (PAGE_EXISTS);
}
}
else if(this.printcomponent instanceof JPanel){
if (pageIndex >= 1) {
return Printable.NO_SUCH_PAGE;
}
if(pageOrientation.equalsIgnoreCase("potrait")){
pageFormat.setOrientation(PageFormat.PORTRAIT);
}else{
pageFormat.setOrientation(PageFormat.LANDSCAPE);
}
Graphics2D g2 = (Graphics2D) g;
double height = pageFormat.getImageableHeight();
double width = pageFormat.getImageableWidth();
int fontWidth = g.getFontMetrics().stringWidth(header);
g2.translate(pageFormat.getImageableX()+10,
pageFormat.getImageableY()+10);
g2.setColor(Color.black);
if(header.trim().length() >0){
g.drawString(header,
( (int) width / 2) - (int) (fontWidth / 2),
0); //header center
}
if(footer.trim().length() >0){
g2.drawString(footer, (int) width / 2,
(int) height - g2.getFontMetrics().getHeight());
}
g2.translate(150f, 160f);
g2.setClip(0, 0, (int) width,
(int) (height - g2.getFontMetrics().getHeight() * 2));
printcomponent.paint(g2);
return Printable.PAGE_EXISTS;
}
}catch(Exception e){
e.printStackTrace();
}
return (PAGE_EXISTS);
}
}