Printing a jpanel

is it possible to print a jpanel i can print individual components but i want to do a printout that contains many components. any advice

You make the JPanel implement the Printable interface. Here's a small code sample that I recently created when I tried to make a printable panel. Note that I've made it so that the buttons don't print:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
public class PrintFrame extends JPanel implements Printable
    private static final int TF_SIZE = 20;
    private JFrame mainFrame = null;
    private NoPrintButton insertData = new NoPrintButton("Insert Data");
    private NoPrintButton printFrame = new NoPrintButton("Print");
    private String[] labelNames =
            "Name", "Age", "Phone Number", "Sex"
    private String[] textValues =
            "John Smith", "55", "555-555-5555", "male"
    private JTextField[] dataFieldArr = new JTextField[labelNames.length];
    public PrintFrame(JFrame mainFrame) {
        super();
        this.mainFrame = mainFrame;
        final int BS = 10;
        setBorder(BorderFactory.createEmptyBorder(BS, BS, BS, BS));
        setLayout(new BorderLayout());
        add(createTextPane(), BorderLayout.CENTER);
        add(createButtonPane(), BorderLayout.SOUTH);
    private JPanel createButtonPane()
        JPanel btnPane = new JPanel();
        btnPane.add(insertData);
        btnPane.add(printFrame);
        insertData.addActionListener(new ButtonListener());
        printFrame.addActionListener(new ButtonListener());
        return btnPane;
    private JPanel createTextPane()
        int labelLength = 100;
        int labelHeight = 20;
        JPanel textPane = new JPanel();
        textPane.setLayout(new GridLayout(0, 1));
        for (int i = 0; i < dataFieldArr.length; i++)
            JPanel rowPane = new JPanel();
            JLabel myLabel = new JLabel(labelNames);
myLabel.setPreferredSize(new Dimension(labelLength, labelHeight));
rowPane.add(myLabel);
dataFieldArr[i] = new JTextField(TF_SIZE);
rowPane.add(dataFieldArr[i]);
textPane.add(rowPane);
return textPane;
private void printPanel()
PrinterJob printJob = PrinterJob.getPrinterJob();
boolean doPrint = printJob.printDialog();
if (doPrint)
printJob.setPrintable(this);
try
printJob.print();
catch (PrinterException pe)
pe.printStackTrace();
public int print(Graphics g, PageFormat pf, int page)
throws PrinterException
if (page > 0)
return NO_SUCH_PAGE;
* User (0,0) is typically outside the imageable area, so we must
* translate by the X and Y values in the PageFormat to avoid clipping
Graphics2D g2d = (Graphics2D) g;
g2d.translate(pf.getImageableX() + 30, pf.getImageableY() + 50);
mainFrame.printAll(g); // if you want to print the JPanel only, then delete "mainFrame." here
return PAGE_EXISTS;
private class ButtonListener implements ActionListener
public void actionPerformed(ActionEvent ae)
NoPrintButton myBtn = (NoPrintButton) ae.getSource();
if (myBtn == insertData)
for (int i = 0; i < dataFieldArr.length; i++)
dataFieldArr[i].setText(textValues[i]);
else if (myBtn == printFrame)
printPanel();
* This is nothing but a plain JButton with the print method overridden by
* a method that does nothing. This will prevent the button from being printed but
* leaves a blank space in the output where the button used to be.
* @author Pete
private class NoPrintButton extends JButton
public NoPrintButton(String text) {
super(text);
@Override
public void print(Graphics g)
// override print method with blank method
private static void createAndShowGUI()
JFrame frame = new JFrame("Print Frame Application");
frame.getContentPane().add(new PrintFrame(frame));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
public static void main(String[] args)
SwingUtilities.invokeLater(new Runnable()
public void run()
createAndShowGUI();
Edited by: petes1234 on Sep 17, 2007 5:36 PM

Similar Messages

  • How can I Print a JPanel including all added Components?

    Hello dear saviours,
    I have a JPanel object which is responsible for displaying a Graph.
    I need to Print the Components of this JPanel as close to what they look like to the user as possible.
    I thought about casting the JPanel into an Image of some kind, but couldn't find anything but how to add am Image to a JPanel (God damned search engines :-).
    But wait, this gets more interesting!
    I need to have control over the scale of the Printed matterial.
    I want the option to choose between a single page and dividing the drawing the JPanel displays into Multiple-Pages.
    In both cases I need full details of all the data (Nodes, Arcs, Text describing the various Nodes and Arcs names or type, etc.).Keeping the sizes of all these components is also important (that means, I don't want the nodes to be tinny-winny and the Fonts to be twice as large as the nodes and so on...).
    Attached is the code of the PrintUtillity class I created as an API for printing the JPanel data:
    package ild;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.print.*;
    /** A simple utility class that lets you very simply print
    * an arbitrary component. Just pass the component to the
    * PrintUtilities.printComponent. The component you want to
    * print doesn't need a print method and doesn't have to
    * implement any interface or do anything special at all.
    * <P>
    * If you are going to be printing many times, it is marginally more
    * efficient to first do the following:
    * <PRE>
    * PrintUtilities printHelper = new PrintUtilities(theComponent);
    * </PRE>
    * then later do printHelper.print(). But this is a very tiny
    * difference, so in most cases just do the simpler
    * PrintUtilities.printComponent(componentToBePrinted).
    * 7/99 Marty Hall, http://www.apl.jhu.edu/~hall/java/
    * May be freely used or adapted.
    public class PrintUtilities implements Printable {
    private Component componentToBePrinted;
    public PrintUtilities(Component componentToBePrinted) {
    this.componentToBePrinted = componentToBePrinted;
    public static void printComponent(Component c) {
    new PrintUtilities(c).print();
    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;
    // double scale = 2;
    // g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    double scaleFactor = java.lang.Math.min((double)this.componentToBePrinted.getSize().width/(double)(pageFormat.getImageableWidth()),
    (double)this.componentToBePrinted.getSize().height/(double)(pageFormat.getImageableHeight()));
    g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    g2d.scale(1.0/scaleFactor,1.0/scaleFactor);
    // disableDoubleBuffering(componentToBePrinted);
    componentToBePrinted.paint(g2d);
    enableDoubleBuffering(componentToBePrinted);
    return(PAGE_EXISTS);
    /** The speed and quality of printing suffers dramatically if
    * any of the containers have double buffering turned on.
    * So this turns if off globally.
    * @see enableDoubleBuffering
    public static void disableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(false);
    /** Re-enables double buffering globally. */
    public static void enableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(true);

    That's a nice utility, but my JPanel gets truncated when printed. Is there a way to print a JPanel in full.

  • Help needed in printing a JPanel in Swing..

    Hi,
    I'm working on a Printing task using Swing. I'm trying to print a JPanel. All i'm doing is by creating a "java.awt.print.Book" object and adding (append) some content to it. And these pages are in the form of JPanel. I've created a separate class for this which extends the JPanel. I've overridden the print() method. I have tried many things that i found on the web and it simply doesn't work. At the end it just renders an empty page, when i try to print it. I'm just pasting a sample code of the my custom JPanel's print method here:
    public int print(Graphics g, PageFormat pageformat, int pagenb)
        throws PrinterException {
    //if(pagenb != this.pagenb) return Printable.NO_SUCH_PAGE;
    Graphics2D g2d = (Graphics2D)g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
            RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
            RenderingHints.VALUE_FRACTIONALMETRICS_ON);
    g2d.setClip(0, 0, this.getWidth(), this.getHeight());
    g2d.setColor(Color.BLACK);
    //disable double buffering before printing
    RepaintManager rp = RepaintManager.currentManager(this);
    rp.setDoubleBufferingEnabled(false);
    this.paint(g2d);
    rp.setDoubleBufferingEnabled(true);
    return Printable.PAGE_EXISTS;     
    }Please help me where i'm going wrong. I'm just trying to print the JPanel with their contents.
    Thanks in advance.

    Hi,
    Try this
    import java.awt.BorderLayout;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.LayoutManager;
    import java.awt.event.ActionEvent;
    import java.awt.print.PageFormat;
    import java.awt.print.Printable;
    import java.awt.print.PrinterException;
    import java.awt.print.PrinterJob;
    import javax.swing.AbstractAction;
    import javax.swing.JColorChooser;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JToolBar;
    import javax.swing.SwingUtilities;
    public class PrintablePanel extends JPanel implements Printable {
        private static final long serialVersionUID = 1L;
        public static void main(String[] args) {
         SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              final PrintablePanel target = new PrintablePanel(
                   new BorderLayout());
              target.add(new JColorChooser());
              frame.add(target, BorderLayout.CENTER);
              JToolBar toolBar = new JToolBar();
              frame.add(toolBar, BorderLayout.PAGE_START);
              toolBar.add(new AbstractAction("Print") {
                  private static final long serialVersionUID = 1L;
                  @Override
                  public void actionPerformed(ActionEvent event) {
                   PrinterJob printerJob = PrinterJob.getPrinterJob();
                   printerJob.setPrintable(target);
                   try {
                       printerJob.print();
                   } catch (PrinterException e) {
                       e.printStackTrace();
              frame.pack();
              frame.setVisible(true);
        public PrintablePanel() {
         super();
        public PrintablePanel(LayoutManager layout) {
         super(layout);
        @Override
        public int print(Graphics g, PageFormat format, int page)
             throws PrinterException {
         if (page == 0) {
             Graphics2D g2 = (Graphics2D) g;
             g2.translate(format.getImageableX(), format.getImageableY());
             print(g2);
             g2.translate(-format.getImageableX(), -format.getImageableY());
             return Printable.PAGE_EXISTS;
         } else {
             return Printable.NO_SUCH_PAGE;
    }Piet
    Edit: Sorry. Just now I see that you want to use the Swing print mechanism. But I guess the implementation of the Printable interface remains the same.
    Edited by: pietblok on 14-nov-2008 17:23

  • Is it possible to print a JPanel from the application?

    Hello,
    Just a quick question: Is it possible to print a JPanel from your application? I have plotted a graph and I would like user to be able to print this with a click of a button (or similar)
    Thanks very much for your help, its appreciated as always.
    Harold Clements

    It is absolutely possible
    Check out my StandardPrint class. Basically all you need to do is
    (this is pseudocode. I don't remember the exact names of methods for all this stuff. Look it up if there's a problem)
    PrinterJob pd = PrinterJob.createNewJob();
    StandardPrint sp = new StandardPrint(yourComponent);
    pd.setPageable(sp);
    //if you want this
    //pd.pageDialog();
    pd.doPrint();You are welcome to have use and modify this class but please don't change the package or take credit for it as your own code.
    StandardPrint.java
    ===============
    package tjacobs.print;
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.awt.print.*;
    import javax.print.PrintException;
    public class StandardPrint implements Printable, Pageable {
        Component c;
        SpecialPrint sp;
        PageFormat mFormat;
         boolean mScale = false;
         boolean mMaintainRatio = true;
        public StandardPrint(Component c) {
            this.c = c;
            if (c instanceof SpecialPrint) {
                sp = (SpecialPrint)c;
        public StandardPrint(SpecialPrint sp) {
            this.sp = sp;
         public boolean isPrintScaled () {
              return mScale;
         public void setPrintScaled(boolean b) {
              mScale = b;
         public boolean getMaintainsAspect() {
              return mMaintainRatio;
         public void setMaintainsAspect(boolean b) {
              mMaintainRatio = b;
        public void start() throws PrinterException {
            PrinterJob job = PrinterJob.getPrinterJob();
            if (mFormat == null) {
                mFormat = job.defaultPage();
            job.setPageable(this);
            if (job.printDialog()) {
                job.print();
        public void setPageFormat (PageFormat pf) {
            mFormat = pf;
        public void printStandardComponent (Pageable p) throws PrinterException {
            PrinterJob job = PrinterJob.getPrinterJob();
            job.setPageable(p);
            job.print();
        private Dimension getJobSize() {
            if (sp != null) {
                return sp.getPrintSize();
            else {
                return c.getSize();
        public static Image preview (int width, int height, Printable sp, PageFormat pf, int pageNo) {
            BufferedImage im = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            return preview (im, sp, pf, pageNo);
        public static Image preview (Image im, Printable sp, PageFormat pf, int pageNo) {
            Graphics2D g = (Graphics2D) im.getGraphics();
            int width = im.getWidth(null);
            int height = im.getHeight(null);
            g.setColor(Color.WHITE);
            g.fillRect(0, 0, width, height);
            double hratio = height / pf.getHeight();
            double wratio = width / pf.getWidth();
            //g.scale(hratio, wratio);
            try {
                   sp.print(g, pf, pageNo);
              catch(PrinterException pe) {
                   pe.printStackTrace();
            g.dispose();
            return im;
        public int print(Graphics gr, PageFormat format, int pageNo) {
            mFormat = format;
            if (pageNo > getNumberOfPages()) {
                return Printable.NO_SUCH_PAGE;
            Graphics2D g = (Graphics2D) gr;
              g.drawRect(0, 0, (int)format.getWidth(), (int)format.getHeight());
            g.translate((int)format.getImageableX(), (int)format.getImageableY());
            Dimension size = getJobSize();
              if (!isPrintScaled()) {
                 int horizontal = getNumHorizontalPages();
                 int vertical = getNumVerticalPages();
                 int horizontalOffset = (int) ((pageNo % horizontal) * format.getImageableWidth());
                 int verticalOffset = (int) ((pageNo / vertical) * format.getImageableHeight());
                 double ratio = getScreenRatio();
                 g.scale(1 / ratio, 1 / ratio);
                 g.translate(-horizontalOffset, -verticalOffset);
                 if (sp != null) {
                     sp.printerPaint(g);
                 else {
                     c.paint(g);
                 g.translate(horizontal, vertical);
                 g.scale(ratio, ratio);
              else {
                 double ratio = getScreenRatio();
                 g.scale(1 / ratio, 1 / ratio);
                   double xScale = 1.0;
                   double yScale = 1.0;
                   double wid;
                   double ht;
                   if (sp != null) {
                        wid = sp.getPrintSize().width;
                        ht = sp.getPrintSize().height;
                   else {
                        wid = c.getWidth();
                        ht = c.getHeight();
                   xScale = format.getImageableWidth() / wid;
                   yScale = format.getImageableHeight() / ht;
                   if (getMaintainsAspect()) {
                        xScale = yScale = Math.min(xScale, yScale);
                   g.scale(xScale, yScale);
                   if (sp != null) {
                        sp.printerPaint(g);
                   else {
                        c.paint(g);
                   g.scale(1 / xScale, 1 / yScale);
                   g.scale(ratio, ratio);
             g.translate((int)-format.getImageableX(), (int)-format.getImageableY());     
            return Printable.PAGE_EXISTS;
        public int getNumHorizontalPages() {
            Dimension size = getJobSize();
            int imWidth = (int)mFormat.getImageableWidth();
            int pWidth = 1 + (int)(size.width / getScreenRatio() / imWidth) - (imWidth == size.width ? 1 : 0);
            return pWidth;
        private double getScreenRatio () {
            double res = Toolkit.getDefaultToolkit().getScreenResolution();
            double ratio = res / 72.0;
            return ratio;
        public int getNumVerticalPages() {
            Dimension size = getJobSize();
            int imHeight = (int)mFormat.getImageableHeight();
            int pHeight = (int) (1 + (size.height / getScreenRatio() / imHeight)) - (imHeight == size.height ? 1 : 0);
            return pHeight;
        public int getNumberOfPages() {
              if (isPrintScaled()) return 1;
            return getNumHorizontalPages() * getNumVerticalPages();
        public Printable getPrintable(int i) {
            return this;
        public PageFormat getPageFormat(int page) {
            if (mFormat == null) {
                PrinterJob job = PrinterJob.getPrinterJob();
                mFormat = job.defaultPage();
            return mFormat;
    }

  • Printing a JPanel (Under pressure)

    I am trying to print a JPanel on which i have displayed information using drawString(). This works grand as long as the inforation all fits on one page. The problem occurs when i have too much information to display and it doesn't fit on one page. I thought that it would print the rest one different pages but this does not happen. Only the information that fits on the first page is printed.
    I'm wondering is there some way of printing over multiple pages.
    Any help would be really helpful.
    Thanks.

    Have you checked out the following webpage? Its from Manning's Swing book tutorial on building a word processor and theres a chapter on printing. It certainly helped me:
    http://manning.com/sbe/files/uts2/Chapter22html/Chapter22.htm

  • Printing a JPanel..............HELP required URGENTLY

    I m doing my application using JPanel which contains labels, textfields and buttons.
    Now I want to print this panel. Is it possible to print a JPanel. IF yes, then plz help me as I m stuck up into this big problem and due to which I m not able to complete my project.
    I tried many codes of printing, but I wasn�t able to print it. One of the code is given below which gives me an error in MouseListener and MouseEvent.
    //*********** Main User Interface Class ************
    public class ComponentPrintingTestUI extends JFrame implements MouseListener {
    //private static MyTextPane myTextPane;
    private static MyJPanel myJPanel;
    public ComponentPrintingTestUI() {
    initComponents();
    private void initComponents() {
    JFrame frame = new JFrame("ComponentPrintingTest");
    //JPanel contentPanel1 = new JPanel();
    //JPanel contentPanel2 = new JPanel();
    JPanel contentPanel3 = new JPanel();
    JPanel contentPanel4 = new JPanel();
    contentPanel3.setMaximumSize(new Dimension(270,170));
    contentPanel3.setMinimumSize(new Dimension(270,170));
    contentPanel3.setPreferredSize(new Dimension(270,170));
    //JButton textPrint = new JButton("Print TextPane");
    //textPrint.addMouseListener(this);
    JButton panelPrint = new JButton("Print JPanel");
    panelPrint.addMouseListener(this);
    //myTextPane = new MyTextPane();
    //myTextPane.setEditable(false);
    myJPanel = new MyJPanel();
    //contentPanel1.add(myTextPane, BorderLayout.CENTER);
    //contentPanel2.add(textPrint, BorderLayout.CENTER);
    contentPanel3.add(myJPanel, BorderLayout.CENTER);
    contentPanel4.add(panelPrint, BorderLayout.CENTER);
    //frame.add(contentPanel1, BorderLayout.NORTH);
    //frame.add(contentPanel2, BorderLayout.CENTER);
    frame.add(contentPanel3, BorderLayout.NORTH);
    frame.add(contentPanel4, BorderLayout.SOUTH);
    frame.setSize(1280,1024);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    public void mouseClicked(MouseEvent arg0) {
    // EditorFrame extends JFrame and has all the, well, editing stuff
    //EditorFrame frame = ClerkUtilities.getEventSourceFrame(e); // method simply grabs the source frame
    //PrintableTextPane tp = frame.getTextPane();
    PrinterJob printJob = PrinterJob.getPrinterJob();
    //PageFormat pf = printJob.defaultPage();
    //pf.setOrientation(PageFormat.LANDSCAPE);
    printJob.setPrintable(myJPanel);
    if (printJob.printDialog())
    try
    printJob.print();
    } // end try
    catch (Exception ex)
    ex.printStackTrace();
    } // end Exception catch
    } // end if
    //*********** Custom JPanel Class *************
    public class MyJPanel extends JPanel implements Printable {
    public MyJPanel() {
    initComponents();
    private void initComponents() {
    this.setMaximumSize(new Dimension(270,170));
    this.setMinimumSize(new Dimension(270,170));
    this.setPreferredSize(new Dimension(270,170));
    this.setBackground(Color.GRAY);
    public void paint(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2 = (Graphics2D) g;
    g2.drawString("Sample drawstring", 20, 20);
    g2.drawString("Bottom line", 20, 150);
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException
    /* get component width and table height */
    Dimension dimension = this.getSize();
    double compWidth = dimension.width;
    double compHeight = dimension.height;
    System.out.println("Comp width: " + compWidth);
    System.out.println("Comp height: " + compHeight);
    Paper card = pageFormat.getPaper();
    card.setImageableArea(0, 0, 153, 243);
    card.setSize(153,243);
    pageFormat.setPaper(card);
    pageFormat.setOrientation(PageFormat.LANDSCAPE);
    /* get page width and page height */
    //double pageWidth = pageFormat.getImageableWidth();
    //double pageHeight = pageFormat.getImageableHeight();
    //double scale = pageWidth / compWidth;
    //double scale = compWidth / pageWidth;
    //System.out.println("Page width: " + pageWidth);
    //System.out.println("Page height: " + pageHeight);
    //System.out.println("Scale: " + scale);
    /* calculate the no. of pages to print */
    //final int totalNumPages= (int)Math.ceil((scale * compHeight) / pageHeight);
    if (pageIndex > 3)
    System.out.println("Total pages: " + pageIndex);
    return(NO_SUCH_PAGE);
    } // end if
    else
    Graphics2D g2d = (Graphics2D)g;
    g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    System.out.println("Coords: " + pageFormat.getImageableX() + ", " + pageFormat.getImageableY());
    g2d.translate( 0f, 0f );
    //g2d.translate( 0f, -pageIndex * pageHeight );
    //g2d.scale( scale, scale );
    this.paint(g2d);
    return(PAGE_EXISTS);
    } // end else
    } // end print()
    //*********** Starter Class **********
    //public class ComponentPrintingTest {
    * @param args
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
    public void run() {
    ComponentPrintingTestUI ui = new ComponentPrintingTestUI();
    //ui.setVisible(true);
    I m a newbie to java and don�t have any idea abt printing of Panel. Plz Plz Plz help me.
    Thanks in advance.

    mansi_b85, next time when you post a question:
    - please use code tags (http://forum.java.sun.com/help.jspa?sec=formatting);
    - don't flag your question as urgent which you have done in 3 of your 4 posts here. This implies that your question is more important than other people's questions and/or your time is more valuable than ours (ours as in people who (try to) answer your question). This is considered rude;
    - try writing whole words instead of that horrible sms-speak (plz and abt)
    - post swing related questions in the swing forum.
    Thanks.

  • Print a JPanel

    I have a JPanel which can be bigger than the screen, and viewing is accomplished with scrollbars. I would like to print this JPanel, which itself has other JPanel's on it. I have so far used the Robot class which does a screen print. It prints the visible part of the JPanel but not the part out of view.
    Any help will be appreciated.

    Component comp = myScrollPane.getViewPort().getView();
    Set comp to be printable.

  • Problem to print a JPanel containing jfreeChart

    I need help
    I am developping an application that should display and print reports with histograms.
    I make the histogram with Jfreechart and put it on a JPanel. the report is a Vector of JPanel.
    1. When i print only the panel containing the JFreechart, the panel is printed but the range axis label
    of JFreechart is inverted.
    2. When i print all the report, nothing appears on the page of the panel containing JFreechart.
    here is my printing code:
    //code
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException {
    if (pageIndex >= docToBePrinted.size()) {
    return (NO_SUCH_PAGE);
    } else {
    componentToBePrinted = docToBePrinted.get(pageIndex);
    //componentToBePrinted.repaint();
    Dimension dim = componentToBePrinted.getSize();
    double scaleX = pageFormat.getImageableWidth() / dim.width;
    double scaleY = pageFormat.getImageableHeight() / dim.height;
    double scale = Math.min(scaleX, scaleY);
    Graphics2D g2D = (Graphics2D) g;
    // g2D.translate(0, 0);
    g2D.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    g2D.scale(scale, scale);
    g2D.setPaintMode();
    disableDoubleBuffering(componentToBePrinted);
    componentToBePrinted.print(g2D);
    g2D.dispose();
    //componentToBePrinted.printAll(g2D);
    enableDoubleBuffering(componentToBePrinted);
    //componentToBePrinted.
    return (PAGE_EXISTS);
    //end of code
    "docToBePrinted" is the report
    Could anyone help me please !

    I have the same problem. Similarly to another entry here, be very careful about how many times you reattempt it. I did it several times, hoping it would work out a kink, and it was on an expensive order, now there are over $2000 of "temporary authorizations" depleting my available credit on my card, and it's been that way for almost a week now.
    I am living overseas, and am unfortunately restricted to dial-up internet to upload this, and it either gets stuck at 64kb/8Mb or just jumps right to 8/8Mb, when there is nothing wrong with the my internet connection.
    I emailed Apple in response to the order cancellation email, and stated that perhaps it was the army firewall I'm behind, asking for the site the program connects to in an attempt to unblock the site if it's inadvertently getting blocked on my end. When they replied they said it's a technical issue and that I can call Apple to talk with someone, where they will determine how much the call will cost. That's outrageous to have something brand new, and have to pay for them to help you on an issue that truly may be as simple as giving out a website.
    In response to an earlier reply, I am using iPhoto 5.0.4, and I just purchased my G5 back in October. Is there a later version to iLife that I'm not finding?
    If anyone finds help with this issue, I would greatly appreciate some tips!
    Thanks so much,
    Dave

  • How do u print a JPanel with all of its contents??

    I have produced a java application and want to add printing facilities to the application.
    I want the user to be able to a print a page (JPanel) which consists of JLabel's, JTextarea's and JTable's. How can this be done????
    Thank you,
    Yuvraj.

    Here is an example using the printer class I sent you the other day:
    package com.cpm.printertest.applet;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.print.*;
    * Applet
    * <P>
    * @author *
    public class CPrinterTest extends JApplet {
       boolean isStandalone = false;
       JPanel jPanel1 = new JPanel();
       JCheckBox jCheckBox1 = new JCheckBox();
       JEditorPane jEditorPane1 = new JEditorPane();
       JList jList1 = new JList();
       JLabel jLabel1 = new JLabel();
       JButton jButton1 = new JButton();
        * Constructs a new instance.
        * getParameter
        * @param key
        * @param def
        * @return java.lang.String
       public String getParameter(String key, String def) {
          if (isStandalone) {
             return System.getProperty(key, def);
          if (getParameter(key) != null) {
             return getParameter(key);
          return def;
       public CPrinterTest() {
        * Initializes the state of this instance.
        * init
       public void init() {
          try  {
             jbInit();
          catch (Exception e) {
             e.printStackTrace();
       private void jbInit() throws Exception {
          this.setSize(new Dimension(400, 400));
          jCheckBox1.setText("jCheckBox1");
          jCheckBox1.setBounds(new Rectangle(205, 34, 90, 25));
          jEditorPane1.setText("jEditorPane1");
          jEditorPane1.setBounds(new Rectangle(123, 104, 152, 151));
          jList1.setBounds(new Rectangle(55, 25, 79, 37));
          jLabel1.setText("jLabel1");
          jLabel1.setBounds(new Rectangle(161, 285, 98, 17));
          jButton1.setText("jButton1");
          jButton1.setBounds(new Rectangle(160, 330, 79, 27));
          jButton1.addActionListener(new java.awt.event.ActionListener() {
             public void actionPerformed(ActionEvent e) {
                jButton1_actionPerformed(e);
          jPanel1.setLayout(null);
          this.getContentPane().add(jPanel1, BorderLayout.CENTER);
          jPanel1.add(jCheckBox1, null);
          jPanel1.add(jEditorPane1, null);
          jPanel1.add(jList1, null);
          jPanel1.add(jLabel1, null);
          jPanel1.add(jButton1, null);
        * start
       public void start() {
        * stop
       public void stop() {
        * destroy
       public void destroy() {
        * getAppletInfo
        * @return java.lang.String
       public String getAppletInfo() {
          return "Applet Information";
        * getParameterInfo
        * @return java.lang.String[][]
       public String[][] getParameterInfo() {
          return null;
        * main
        * @param args
       public static void main(String[] args) {
          CPrinterTest applet = new CPrinterTest();
          applet.isStandalone = true;
          JFrame frame = new JFrame();
          frame.setTitle("Applet Frame");
          frame.getContentPane().add(applet, BorderLayout.CENTER);
          applet.init();
          applet.start();
          frame.setSize(400, 420);
          Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
          frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2);
          frame.setVisible(true);
          frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } });
       static {
          try {
             UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
          catch(Exception e) {
             e.printStackTrace();
       void jButton1_actionPerformed(ActionEvent e) {
          CPrintUtilities p = new CPrintUtilities();
          p.AddPage(jPanel1);
          p.print();
    }

  • Printing JPanel that is added to the JScrollPane

    Hi
    I am facing a typical problem while I am printing my JPanel.
    My Panel is added to the JScrollPane.And I added 200 Images to the JPanel (20 rows and 10 columns).
    To see the 6,7,8,9,10 Images I have to scroll it left side and for 80 to 200 images I have to scroll down.
    Now if i print my JPanel it is only printing the Images those are visible to the user at a time. If scroll down and say print again it is printing the bottom components and missing Top components (Images).
    I want to print all the images at a time.
    Can any body suggest me how to do it. My Panel implements Printable interface and the following is the print method that I implemented
    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());
    componentToBePrinted.paintAll(g2d);
    return(PAGE_EXISTS);
    Thank you and Regards
    Kiran Kumar Vasireddy

    could you publish the entire code or at least your paintall method....
    Loic

  • Printing jpanel problem

    So I am trying to print a JPanel. When I print to a pdf after bringing up a page setup dialog and a print dialog, either one of two things is happening.
    1) all drawn lines are shifted down and to the right.
    or
    2) all text is shifted up and to the left.
    Everything on the screen of the program looks great. I think it might have something to do with the fact that I am deriving fonts by scaling them. This would not be a problem if everything was shifting. It is clear that when rendered to a pdf it is handling the text of the fonts that I am using somehow differently than all the lines I am drawing. I do not understand why this is happening. Everything looks so good on the screen.
    If anybody knows what this problem is, your help would be much appreciated.
    Thanks in advance!

    Oh... it's just a mistake because of copy and paste.
    I did also have these code (without if (pageIndex > 0) {
    return(NO_SUCH_PAGE); ) but with these
    /* calculate the no. of pages to print */
    int totalNumPages = (int)Math.ceil((panelHeight) /
    height );
    if (pageIndex >= totalNumPages) return NO_SUCH_PAGE;
    and when I use :
    System.out.println("totalNumPages: " + String.valueOf(totalNumPages));
    I can see at there are two pages. But when it prints it can only print one. So...

  • Printing JPanel ,how do i do it

    Hi,
    I am pasting a code below, which will build a screen with 2 panels in a JSCrollPane, added to a JSplitPane in left and right sides,
    so it will look some thing like below
    | | |
    | | |
    | | |
    | | |
    |___|__________|
    Now i want to provide a funtion to print this , but i dont want to print all the panel on right side, but only a portion, say from 100 to 500 on x-axis, along with the panel on left side
    So how can i do it, i am attaching the code to build this screen can anyone help by providing some code or info about printing it
    Ashish
    //start code
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.util.*;
    import java.io.*;
    import java.awt.print.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.event.*;
    import javax.swing.filechooser.*;
    public class TestPanelPrinting extends JFrame implements ActionListener
         private MyTotalPanel totalPanel;
         public TestPanelPrinting()
         super("Print Frame");
         this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    JMenuBar menuBar = new JMenuBar();
    JMenu menu = new JMenu("print");
    JMenuItem print = new JMenuItem("Print Preview");
         print.addActionListener(this);
         menu.add(print);
         menuBar.add(menu);
    totalPanel = new MyTotalPanel();
         this.setJMenuBar(menuBar);
    this.getContentPane().add(totalPanel);
         this.setSize(1000,700);
    show();
         public void actionPerformed(ActionEvent evt)
         //do printing here
         public class MyTotalPanel extends JPanel
              public MyTotalPanel()
              Data data = new Data();
              MyLeftPanel leftPanel = new MyLeftPanel(data);     
              MyPanel myPanel = new MyPanel(data);
              JScrollPane jsLeft = new JScrollPane(leftPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);     
              JScrollPane jsRight = new JScrollPane(myPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);     
              JSplitPane totalSplit = new JSplitPane();
         totalSplit.setOrientation(JSplitPane.HORIZONTAL_SPLIT);
         totalSplit.setLeftComponent(jsLeft);
         totalSplit.setRightComponent(jsRight);
         totalSplit.setDividerLocation(100);
         totalSplit.setDividerSize(2);
         ((javax.swing.plaf.basic.BasicSplitPaneUI) totalSplit.getUI()).getDivider().setEnabled(false);
         int totalWidth = (int)leftPanel.getPreferredSize().getWidth() + (int)myPanel.getPreferredSize().getWidth() ;
         int totalHeight = (int)leftPanel.getPreferredSize().getHeight() ;
         this.setLayout(new BorderLayout());
         this.setPreferredSize(new Dimension(totalWidth , totalWidth));
         this.add(totalSplit, BorderLayout.SOUTH);
         public class MyLeftPanel extends JPanel
              private int height;
              private int last;
              private Data data;
              public MyLeftPanel(Data data)
                        this.setBackground(Color.white);
                        this.setOpaque(true);
                        this.data = data;
                        int size = data.getSize();
                        height = size * 50;     
                        setPreferredSize(new Dimension(100, height) );
                   public void paintComponent(Graphics g)
         super.paintComponent(g);
         setBackground(Color.white);
    // Rectangle r = g.getClipBounds();
         g.setColor(Color.blue);
         int size = data.getSize();
    int width = 30;
    int height = 20;
    int yAxis = 20;
    for(int i = 0; i < size; i++)
         int dataSize = data.getDataSize(i);
         g.setColor(Color.green);
    //     for(int k = 0; k < dataSize; k++)
              g.drawLine(0, yAxis, 100, yAxis );
              g.setColor(Color.red);
              g.drawString(String.valueOf(yAxis), 10, yAxis + 15);          
         yAxis = yAxis + 50;
         class MyPanel extends JPanel
              private int height;
              private int last;
              private Data data;
              private int length;
              public MyPanel(Data data)
                   this.setBackground(Color.white);
                   this.setOpaque(true);
                   this.data = data;
                   int size = data.getSize();
                   height = size * 50;     
                   last = data.getDataSize(0);
                   int last1 = last -1;
                   length = data.getX(0, last1) + 100;
                   System.out.println ("Lenght " + length + " height " + height);
                   setPreferredSize(new Dimension(length, height) );     
         public void paintComponent(Graphics g)
    super.paintComponent(g);
    setBackground(Color.white);
    // Rectangle r = scrollPane.getViewport().getViewRect();
    // g.setClip((Shape)r);
    // Rectangle r = g.getClipBounds();
    g.setColor(Color.blue);
    int x = 0;
    for(int i = 0; i < last ; i++)
         x +=60;
         g.drawLine(x, 0, x, height);
         g.drawString(String.valueOf(i), x, 10);
    int size = data.getSize();
    int width = 30;
    int height = 20;
    int yAxis = 20;
    for(int i = 0; i < size; i++)
         g.setColor(Color.cyan);     
         int dataSize = data.getDataSize(i);
         for(int k = 0; k < dataSize; k++)
              int xAxis = data.getX(i, k);
         //      if(data.isInView(xAxis- 30, width+ 30,height+ 10 ,yAxis -10,r))
    //     if (r.contains(xAxis, yAxis) || r.contains(xAxis+width, yAxis+height))
              g.fill3DRect(xAxis, yAxis, width, height, true);
         g.setColor(Color.green);
         g.drawLine(0, yAxis, length, yAxis);
         yAxis = yAxis + 50;
    private class Data
              private ArrayList totalData = new ArrayList();
              public Data()
                        for(int i = 0; i < 50; i++)
                        ArrayList data = new ArrayList();
                        int l = 50;
                        for(int k = 0; k < 50; k++)
                             data.add(new Integer(l));
                             l = l + 50;
                        totalData.add(data);
              public int getSize()
                   return totalData.size();     
              public int getDataSize(int i)
                   return ((ArrayList)totalData.get(i)).size();     
              public int getX(int x, int y)
                   ArrayList data = (ArrayList)totalData.get(x);
                   Integer i = (Integer)data.get(y);
                   return i.intValue();
              public boolean isInView(int xAxis, int width, int height, int yAxis, Rectangle r)
              //     System.out.println ("xAxis " + xAxis + " yAxis " + yAxis + " width " + width + " height " + height);
                   Rectangle phase = new Rectangle(xAxis, yAxis, width, height);
                   boolean flag=     r.contains(phase);
                   return flag;
    public static void main(String args[])
         new TestPanelPrinting();
    //end code

    You can print the JPanel or infact any java.awt.Component by breaking into multiple pages using the Smart JPrint APIs at http://www.activetree.com
    You can look at the online demo program that shows how to print any component along with printing support for vistually any swing and Java program output.
    The Smart JPrint API also generates a PDF document for the same printable output pages.

  • Urgent- Printing JPanel problem

    I want to print a JPanel by calling a Print utility class. JPanel is drawing with different shapes (Rectangle2D etc..)
    The problem is that I can only print the first page of the JPanel.
    My Print utility:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.print.*;
    public class PrintUtilities {
    private Component componentToBePrinted;
    public static void printComponent(Component c) {
    new PrintUtilities(c).print();
    public PrintUtilities(Component componentToBePrinted) {
    this.componentToBePrinted = componentToBePrinted;
    public void print() {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    BookComponentPrintable printable1 = new BookComponentPrintable(componentToBePrinted);
    PageFormat pageFormat1 = printJob.pageDialog(printJob.defaultPage());
    Book book = new Book();
    book.append(printable1, pageFormat1);
    // Print the Book.
    printJob.setPageable(book);
    if (printJob.printDialog())
    try {
    printJob.print();
    } catch(PrinterException pe) {
    System.out.println("Error printing: " + pe);
    class BookComponentPrintable
    implements Printable {
    private Component mComponent;
    public BookComponentPrintable(Component c) {
    mComponent = c;
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
    if (pageIndex > 0) {
    return(NO_SUCH_PAGE);
    else
    Graphics2D g2 = (Graphics2D)g;
    g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    mComponent.paint(g2);
    return Printable.PAGE_EXISTS;
    What did I do wrong? Thanks in advance !!!

    Oh... it's just a mistake because of copy and paste.
    I did also have these code (without if (pageIndex > 0) {
    return(NO_SUCH_PAGE); ) but with these
    /* calculate the no. of pages to print */
    int totalNumPages = (int)Math.ceil((panelHeight) /
    height );
    if (pageIndex >= totalNumPages) return NO_SUCH_PAGE;
    and when I use :
    System.out.println("totalNumPages: " + String.valueOf(totalNumPages));
    I can see at there are two pages. But when it prints it can only print one. So...

  • Printing JPanel results with a blank page

    I have been trying to print a JPanel with out any luck, I've read the various examples, http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-Printing.html and http://java.sun.com/developer/technicalArticles/Printing/SwingPrinting/
    I can get the print dialog no problem and the printer starts up and prints, but theres nothing on the sheet.
    Am I missing something entirely?
    main screen
    private void printButtonActionPerformed(java.awt.event.ActionEvent evt) {
                 Memo m= new Memo(); // the JPanel to print
                 m.componentToPrint(m);
                 PrinterJob printJob = PrinterJob.getPrinterJob();
                 printJob.setPrintable(m);
                 if (printJob.printDialog())
                 try
                    printJob.print();
                 catch(PrinterException ex)
                    System.out.println("Error printing: " + ex.getMessage());
    }The JPanel to print
    package nonconforming;
    import java.awt.Component;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.print.PageFormat;
    import java.awt.print.Printable;
    import java.awt.print.PrinterException;
    import javax.swing.RepaintManager;
    public class Memo extends javax.swing.JPanel implements Printable{
        /** Creates new form Memo */
        public Memo() {
            initComponents();
        private void initComponents() {
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            jLabel3 = new javax.swing.JLabel();
            jLabel4 = new javax.swing.JLabel();
            jLabel5 = new javax.swing.JLabel();
            jLabel6 = new javax.swing.JLabel();
            setBackground(new java.awt.Color(255, 255, 255));
            jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/nonconforming/bgmlogo.png"))); // NOI18N
            jLabel2.setFont(new java.awt.Font("Arial", 1, 18));
            jLabel2.setText("BGM Fastener Co., Inc.");
            jLabel3.setFont(new java.awt.Font("Arial", 0, 11));
            jLabel3.setText("759 Old Willow Ave. Honesdale, PA 18431");
            jLabel4.setFont(new java.awt.Font("Arial", 0, 11));
            jLabel4.setText("Phone: 800-233-4270/570-253-5046/FAX 570-253-2469");
            jLabel5.setFont(new java.awt.Font("Arial", 0, 11));
            jLabel5.setText("Email: [email protected] Website: http://bgmfastener.com");
            jLabel6.setFont(new java.awt.Font("Dialog", 2, 36));
            jLabel6.setText("MEMO");
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
            this.setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jLabel3)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel2)
                                        .addContainerGap(103, Short.MAX_VALUE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel4)
                                        .addContainerGap(32, Short.MAX_VALUE))
                                    .addComponent(jLabel5))))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(38, 38, 38)
                            .addComponent(jLabel6))))
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addComponent(jLabel2)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jLabel3)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jLabel4)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(jLabel5)
                            .addGap(18, 18, 18)
                            .addComponent(jLabel6)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel1)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                    .addContainerGap(62, Short.MAX_VALUE))
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JLabel jLabel4;
        private javax.swing.JLabel jLabel5;
        private javax.swing.JLabel jLabel6;
        // End of variables declaration                  
        private Component printComponent;
    public void componentToPrint(Component c)
        printComponent=c;
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException{
            if (pageIndex > 0)
              return(NO_SUCH_PAGE);
            else
              Graphics2D g2d = (Graphics2D)g;
              g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
              // Turn off double buffering
              disableDoubleBuffering(printComponent);
              printComponent.paint(g2d);
              // Turn double buffering back on
              enableDoubleBuffering(printComponent);
              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);
    }Thank you for any help

    Search google for "StandardPrint.java" and you will find my StandardPrint class. That should be all you need :)

  • Print Jpanel (linux?)

    I'm trying to print a JPanel and use the following code which should work. When I try to print I get the following error "no print service found".
    Through google I've found other people having the same problem printing from java applications in linux. Does anybody have any ideas/fixes?
    Cheers,
    Ally
    Used to print a component:
    public class PrintUtilities implements Printable {
    private Component componentToBePrinted;
    public static void printComponent(Component c) {
    new PrintUtilities(c).print();
    public PrintUtilities(Component componentToBePrinted) {
    this.componentToBePrinted = componentToBePrinted;
    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(componentToBePrinted);
    componentToBePrinted.paint(g2d);
    enableDoubleBuffering(componentToBePrinted);
    return(PAGE_EXISTS);
    /** The speed and quality of printing suffers dramatically if
    * any of the containers have double buffering turned on.
    * So this turns if off globally.
    * @see enableDoubleBuffering
    public static void disableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(false);
    /** Re-enables double buffering globally. */
    public static void enableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(true);

    Ally: I have a little print test demo I just did. Try it and see if that works in your linux environment.
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import com.cpm.common.utilities.*;
    import java.awt.print.*;
    import java.awt.geom.Line2D;
    import java.awt.geom.Point2D;
    * Applet
    * <P>
    * @author *
    public class CPrinterTest extends JApplet {
       boolean isStandalone = false;
    //   JPanel jPanel1 = new JPanel();
       MyPanel jPanel1 = new MyPanel();
       JCheckBox jCheckBox1 = new JCheckBox();
       JEditorPane jEditorPane1 = new JEditorPane();
       JList jList1 = new JList();
       JLabel jLabel1 = new JLabel();
       JButton jButton1 = new JButton();
        * Constructs a new instance.
        * getParameter
        * @param key
        * @param def
        * @return java.lang.String
       public String getParameter(String key, String def) {
          if (isStandalone) {
             return System.getProperty(key, def);
          if (getParameter(key) != null) {
             return getParameter(key);
          return def;
       public CPrinterTest() {
        * Initializes the state of this instance.
        * init
       public void init() {
          try  {
             jbInit();
          catch (Exception e) {
             e.printStackTrace();
       private void jbInit() throws Exception {
          this.setSize(new Dimension(400, 400));
          jCheckBox1.setText("jCheckBox1");
          jCheckBox1.setBounds(new Rectangle(205, 34, 90, 25));
          jEditorPane1.setText("jEditorPane1");
          jEditorPane1.setBounds(new Rectangle(123, 104, 152, 151));
          jList1.setBounds(new Rectangle(55, 25, 79, 37));
          jLabel1.setText("jLabel1");
          jLabel1.setBounds(new Rectangle(161, 285, 98, 17));
          jButton1.setText("jButton1");
          jButton1.setBounds(new Rectangle(160, 330, 79, 27));
          jButton1.addActionListener(new java.awt.event.ActionListener() {
             public void actionPerformed(ActionEvent e) {
                jButton1_actionPerformed(e);
          jPanel1.setLayout(null);
          this.getContentPane().add(jPanel1, BorderLayout.CENTER);
          jPanel1.add(jCheckBox1, null);
          jPanel1.add(jEditorPane1, null);
          jPanel1.add(jList1, null);
          jPanel1.add(jLabel1, null);
          jPanel1.add(jButton1, null);
        * start
       public void start() {
        * stop
       public void stop() {
        * destroy
       public void destroy() {
        * getAppletInfo
        * @return java.lang.String
       public String getAppletInfo() {
          return "Applet Information";
        * getParameterInfo
        * @return java.lang.String[][]
       public String[][] getParameterInfo() {
          return null;
        * main
        * @param args
       public static void main(String[] args) {
          CPrinterTest applet = new CPrinterTest();
          applet.isStandalone = true;
          JFrame frame = new JFrame();
          frame.setTitle("Applet Frame");
          frame.getContentPane().add(applet, BorderLayout.CENTER);
          applet.init();
          applet.start();
          frame.setSize(400, 420);
          Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
          frame.setLocation((d.width - frame.getSize().width) / 2, (d.height - frame.getSize().height) / 2);
          frame.setVisible(true);
          frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } });
       static {
          try {
             UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
          catch(Exception e) {
             e.printStackTrace();
       void jButton1_actionPerformed(ActionEvent e) {
          CPrintUtilities p = new CPrintUtilities();
          JPanel clone = jPanel1;
          clone.setSize(500,500);
          p.AddPage(clone);
          p.print();
    class MyPanel extends JPanel {
       public void paintComponent(Graphics g)
          super.paintComponent(g);
          Line2D.Float l1 = new Line2D.Float(0,0,400,400);
          Line2D.Float l2 = new Line2D.Float(400,400,0,0);
          boolean bYes = l1.intersectsLine(400,400,400,400);
          System.out.println(bYes);
    }And here is the CPrintUtilities class;
    package com.cpm.common.utilities;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.print.*;
    import java.awt.event.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import java.util.*;
    /** A simple utility class that lets you very simply print
    *  an arbitrary component. Just pass the component to the
    *  PrintUtilities.printComponent. The component you want to
    *  print doesn't need a print method and doesn't have to
    *  implement any interface or do anything special at all.
    *  <P>
    *  If you are going to be printing many times, it is marginally more
    *  efficient to first do the following:
    *  <PRE>
    *    PrintUtilities printHelper = new PrintUtilities(theComponent);
    *  </PRE>
    *  then later do printHelper.print(). But this is a very tiny
    *  difference, so in most cases just do the simpler
    *  PrintUtilities.printComponent(componentToBePrinted).
    public class CPrintUtilities implements Printable
      private Component componentToBePrinted;
      protected Book m_book = new Book();
      protected ArrayList m_arrayPages  = new ArrayList();
      protected double m_scaleFactorX = 1.0f;
      protected double m_scaleFactorY = 1.0f;
      protected boolean m_bShowPrintDialog = true;
      protected static PrinterJob printJob = null;
      public static void printComponent(Component c)
        new CPrintUtilities(c).print();
      public CPrintUtilities(Component componentToBePrinted)
        this.componentToBePrinted = componentToBePrinted;
      public CPrintUtilities()
      public CPrintUtilities(Book book)
        m_book = book;
      public void AddPage(Component componentToBePrinted)
         m_arrayPages.add(componentToBePrinted);
      public void SetShowPrintDialog(boolean bShowPrintDialog)
         m_bShowPrintDialog = bShowPrintDialog;
    //   public void print()
       public boolean print()
          printJob = PrinterJob.getPrinterJob();
    //      if(printJob.printDialog()) {
          if(m_bShowPrintDialog) {
             if(!printJob.printDialog())  {
                return false;
          try {
             // Revise the Page Format
             PageFormat format = printJob.defaultPage();
             double nMargin = 72/4;  // Inch / 4 or one quarter inch
             Paper paper = format.getPaper();
             double nHeight = paper.getHeight() - (nMargin * 2);
             double nWidth  = paper.getWidth()  - (nMargin * 2);
             double scaleFactorX = 1.0f;
             double scaleFactorY = 1.0f;
             paper.setImageableArea(nMargin,nMargin,nWidth,nHeight);
             format.setPaper(paper);
             for(int x = 0;x < m_arrayPages.size();x++) {
                componentToBePrinted = (Component)m_arrayPages.get(x);
                // Scale to print
                double nCompHeight = componentToBePrinted.getHeight();
                double nCompWidth  = componentToBePrinted.getWidth();
                if (nWidth > nCompWidth)
                  scaleFactorX = nCompWidth / nWidth;
                else
                  scaleFactorX = nWidth / nCompWidth;
                if (nHeight > nCompHeight)
                  scaleFactorY = nCompHeight / nHeight;
                else
                  scaleFactorY = nHeight / nCompHeight;
                m_scaleFactorX = scaleFactorX;
                m_scaleFactorY = scaleFactorY;
                printJob.setPrintable(this,format);
                printJob.print();
          catch(PrinterException pe) {
             CSystem.PrintDebugMessage("Error printing: " + pe);
          return true;
       public void printBook()
          PrinterJob printJob = PrinterJob.getPrinterJob();
          if (printJob.printDialog())
             try
                for(int x = 0;x < m_book.getNumberOfPages();x++)
                   Printable printable = m_book.getPrintable(x);
                   printJob.setPrintable(printable);
                   printJob.print();
             catch(PrinterException pe)  {
                CSystem.PrintDebugMessage("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());
          g2d.scale(m_scaleFactorX,m_scaleFactorY);
          disableDoubleBuffering(componentToBePrinted);
          componentToBePrinted.paint(g2d);
          enableDoubleBuffering(componentToBePrinted);
          return(PAGE_EXISTS);
      /** The speed and quality of printing suffers dramatically if
       *  any of the containers have double buffering turned on.
       *  So this turns if off globally.
       *  @see enableDoubleBuffering
      public static void disableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(false);
      /** Re-enables double buffering globally. */
      public static void enableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(true);
    }

Maybe you are looking for

  • After I sync my IPhone with Outlook, some contacts only appear on the IPhone and NOT in Outlook

    I have been syncing my phone with Outlook for some time successfully but just noticed that there are now contacts on my Iphone which don't appear in my Outlook contacts. I also noticed that those that appear in both places have "linked cards" on thei

  • Doubt with creation of Model in the application Webdynpro Java

    Good Morning, I have the following doubts with the fields when i am creating a models in WebDynpro Java Model Package Source Fólder Default logical system name for model instances Default logical system name for RFC metadata Logical Dictionary Dictio

  • Idoc to file scenario general query

    Hi All, I know about the basic settings needed for the Idoc to file scenario. My query is related the idoc /ALE settings. I have a scenatio wrking in my system where we have configured the port for B type partner and also the port as XML-HTTP I can n

  • Iphone could not be restored error?

    Trying to do routine update on my iPhone 4.  Then was prompted to restore my phone to original settings. Went through 3 hours of that, then an error occured saying unable to restore the phone.  Now, I can't do anything with my phone.  Tried disconnec

  • DHCP Settings keep resetting?

    I've actually had this problem since Server 2 for Mountain Lion, and removing Server and /Library/Server would do the trick, but not with Server 3.1... Any ideas?  To be clear, every time I set the DHCP settings and enable the DHCP service, it will r