Tuesday, March 3, 2009

Print Swing Components in JAVA

Few days back, I have been asked for an assignment from my workgroup that will print a swing component. This was really new task for me, as I have never experienced it.

After digging through the internet, I could easily find out that JDK 6 itself has the provision of printing the Swing components. The package that it deals with is the java.awt.print package. The documentation link for the above package is: http://java.sun.com/javase/6/docs/api/index.html?java/awt/print/package-summary.html

The source code I found is very straight forward to explain as it first creates simple java frame. The class you will be using should extend JFrame to make it a Swing Component and it should implement Printable class to make it a pointer (Not technical terms) to printable object.

The following line of code is the backbone for printing the Swing Components:

public void print() {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
if (printJob.printDialog())
try {
printJob.print();
} catch(PrinterException pe) {
System.out.println("Error printing: " + pe);
}
}

public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
if (pageIndex > 0) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
disableDoubleBuffering(this);
this.paint(g2d);
enableDoubleBuffering(this);
return(PAGE_EXISTS);
}
}

The PrinterJob class is the principal class that controls printing. An application calls methods in this class to set up a job, optionally to invoke a print dialog with the user, and then to print the pages of the job.

The setPrintable() calls painter to render the pages. The pages in the document to be printed by this PrinterJob are rendered by the Printable object, painter.

Following is the whole set of code that first creates a Swing Component and then prints it.

package printswing;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.AffineTransform;
import java.awt.print.PageFormat;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.RepaintManager;
import java.awt.*;
import javax.swing.*;
import java.awt.print.*;
import javax.swing.UIManager;

public class Main extends JFrame implements ActionListener,Printable{

/** Creates a new instance of PrintEntire */
public Main() {
super("An example of printing swing components");
setNativeLookAndFeel();
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
Container content = getContentPane();
JButton printButton = new JButton("Print");
printButton.setActionCommand("Print");
printButton.addActionListener(this);
JPanel buttonPanel = new JPanel();
buttonPanel.setBackground(Color.white);
buttonPanel.add(printButton);
content.add(buttonPanel, BorderLayout.SOUTH);
DrawingPanel drawingPanel = new DrawingPanel();
content.add(drawingPanel, BorderLayout.CENTER);
pack();
setVisible(true);
}


public void actionPerformed(ActionEvent ae){
if(ae.getActionCommand().equals("Print")){
this.print();
}
}


public static void setNativeLookAndFeel() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch(Exception e) {
System.out.println("Error setting native LAF: " + e);
}
}

public static void setJavaLookAndFeel() {
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch(Exception e) {
System.out.println("Error setting Java LAF: " + e);
}
}

public static void setMotifLookAndFeel() {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
} catch(Exception e) {
System.out.println("Error setting Motif LAF: " + e);
}
}

/** A simplified way to see a JPanel or other Container.
* Pops up a JFrame with specified Container as the content pane.
*/

public static JFrame openInJFrame(Container content,
int width,
int height,
String title,
Color bgColor) {
JFrame frame = new JFrame(title);
frame.setBackground(bgColor);
content.setBackground(bgColor);
frame.setSize(width, height);
frame.setContentPane(content);
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
frame.setVisible(true);
return(frame);
}

/** Uses Color.white as the background color. */

public static JFrame openInJFrame(Container content,
int width,
int height,
String title) {
return(openInJFrame(content, width, height, title, Color.white));
}

/** Uses Color.white as the background color, and the
* name of the Container's class as the JFrame title.
*/

public static JFrame openInJFrame(Container content,
int width,
int height) {
return(openInJFrame(content, width, height,
content.getClass().getName(),
Color.white));
}


public void print() {
PrinterJob printJob = PrinterJob.getPrinterJob();
printJob.setPrintable(this);
if (printJob.printDialog())
try {
printJob.print();
} catch(PrinterException pe) {
System.out.println("Error printing: " + pe);
}
}

public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
if (pageIndex > 0) {
return(NO_SUCH_PAGE);
} else {
Graphics2D g2d = (Graphics2D)g;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
disableDoubleBuffering(this);
this.paint(g2d);
enableDoubleBuffering(this);
return(PAGE_EXISTS);
}
}

public static void disableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(false);
}

public static void enableDoubleBuffering(Component c) {
RepaintManager currentManager = RepaintManager.currentManager(c);
currentManager.setDoubleBufferingEnabled(true);
}

public static void main(String args[]){
new Main();
}

class DrawingPanel extends JPanel {
private int fontSize = 90;
private String message = "Java 2D";
private int messageWidth;

public DrawingPanel() {
setBackground(Color.white);
Font font = new Font("Serif", Font.PLAIN, fontSize);
setFont(font);
FontMetrics metrics = getFontMetrics(font);
messageWidth = metrics.stringWidth(message);
int width = messageWidth*5/3;
int height = fontSize*3;
setPreferredSize(new Dimension(width, height));
}

public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
int x = messageWidth/10;
int y = fontSize*5/2;
g2d.translate(x, y);
g2d.setPaint(Color.lightGray);
AffineTransform origTransform = g2d.getTransform();
g2d.shear(-0.95, 0);
g2d.scale(1, 3);
g2d.drawString(message, 0, 0);
g2d.setTransform(origTransform);
g2d.setPaint(Color.black);
g2d.drawString(message, 0, 0);
}
}
}

No comments:

Total Pageviews