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;
}

Similar Messages

  • Is it possible to print a note from numbers spreadsheet

    Hi I hope someone can help. Is it possible to print a note from numbers spreadsheet. Or is there any way I can type a ticket that I can print but that will automatically transfer the data to a spreadsheet in numbers?

    How about the opposite direction. You have a table with a "key" field, like a ticket #.
    You make another sheet that you type in the ticket number and it pulls up the proper data in the proper location for you to print. Just a print tempalte that fills out for the ticket already entered into the data table.
    Jason

  • My Mac won't print a pdf from the web

    My iMac will not print any pdf from the web. The printer (an ho Photosmart plus) will only print a blank shet of paper.

    Try saving the file then, then open Preview and open the file and try printing again. If if the quality is still bad then it's the file itself.

  • Message- Print No pages from the document were selected to be printed

    I have had this application for some time, simply never used it.  Last night I tried converting a PDF file to word, unsuccessfully, I might add.
    Today, whilst printing a page, my printing settings appear to have been reset because when I selected Print selected page, the following message appeared:
    Print
         No pages from the document were selected to be printed message
    How do I reconfigure my settings to preview rather than defaulting to PDF?  Kindly advise.  Cheers.

    I have only been able to print by exporting from iphoto. I have a new HP printer and there is software that supports photo printing ("HP photo smart") and I have been able to do it this way. On some occasions I have been able to use the iphoto>print>then preview before actually printing. There is a print option on the preview pane and that has worked on occasion...unsure why it doesn't work always. Please pass on any other hints, or let me know if this works for you!!
    G4 Power book 867Mhz   Mac OS X (10.3.9)  

  • Is there a possibility to open raw files from the Nikon D750 in photoshop elements 11?

    Is there a possibility to open raw files from the Nikon D750 in photoshop elements 11? I allready tried to install camera raw 8.7.1 but it doesn't work.

    Yes, I see:
    Letzte Aktualisierung
    16.04.2012
    The link I gave is listed in the faqs of this forum.
    Photoshop Elements FAQ List
    mfG
    Michel

  • Is it possible to retrieve deleted items from the Pages App please?

    IIs it possible to retrieve deleted items from the Pages App? Thanks

    From within the Pages app, no. If you have an iTunes or iCloud backup that would have contained the file, and you are backing up Pages, it could be received via a restore using that backup (this would wipe out any newer data however).

  • Is it possible to delete a relationship from the BP ?

    Hello experts,
    I'd would like to replace a function partner SH (having the same number as the DO) by another  from R3 to CRM5.
    At the begining i have in R3 this partner
    AG 3901007
    RE 3901007
    RG 3901007
    WE 3901007
    In R3 by the transaction VD02, I replace the partner SH by another
    After the modify i have in R3.
    AG 3901007
    RE 3901007
    RG 3901007
    WE 5000000
    When the replication is done in CRM using BDOC, i can see, by the transaction BP
    the new ship to party partner(5000000) .
    The trouble is :
    When customer access to ISA (standard version) to order product, he can select the partner 3901007 as shipping adress.
    By ISA, he should have the partner 5000000 only.
    Is it standard or is it a sap trouble ?
    Is it possible to delete a relationship from the BP ?
    I don't want to delete the BP partner, i just want to delete the relationship when then BDOC arrive in CRM.
    i have found the oss note 596334 497146 757955 too but it doesn't bring me a solution.
    Best regards
    Christophe

    Hello
    When you delete a Partner Function in R/3 the corresponding relationshipdoesn't get deleted in CRM. This is standard SAP behavior and not a
    bug. Reason for this behavior has been explained in Note 490454.
    You can change this behavior by implementing Note 497146. Also check
    the note 682427 which will help you in clearing old data.

  • Is it possible to run process chain from the certain process/point?

    Hello
    Is it possible to run process chain from the certain process?
    How?
    Thanks

    Hello,
    yes it possible! use the following steps.
    1. Goto the process which you want the chain to start from.Goto display messages>> Chain tab. In the generated instance note the variant and instance.
    2. Goto table RSPROCESSLOG and give variant and instance and get logid details.
    3. t codese37>> run FM RSPROCESSFINISH.
    4. give the deatils u have got in RSPROCESSLOG table here and say execute.
    This will solve ur problem.
    Hope this helps!
    Reg
    Deepmala

  • Is it possible to reference one cell from the value of another?

    Is it possible to reference one cell from the value of another e.g.
    value of b1 = value of c(value of a1)
    So if a1 = 3 then b1 = c3, if a1 = 5 then b1 = c5.

    Excellent!
    Thanks Wayne. Just saved me many hours and a headache.
    Works like a dream.
    Thank you for your succinct (and accurate) answer.
    Mark

  • Is it possible to recover deleted files from the Microsoft Word app for iPhone? I am desperate.

    Is it possible to recover deleted files from the Microsoft Word app for iPhone? I am desperate.

    From the Microsoft Word app they say "Access Word documents from OneDrive, Dropbox, iCloud, OneDrive for Business, or SharePoint" so it sounds like you can specify where they are saved. However, my guess would be that the default will be OneDrive.
    To the OP: Have you tried logging into onedrive.live.com to see if you can see your letter there?

  • Is it possible to retrieve deleted files from the cloud i.e. contact list?

    Is it possible to retrieve deleted files from the cloud i.e. contacts?

    If you have an iCloud backup of an iOS device that was made while the contacts were still on it, you may be able to restore them from the backup by following this user tip from Winston Churchill: https://discussions.apple.com/docs/DOC-4841.

  • Is it possible to recover wrongly erased (from the iCloud) emails?

    Is it possible to recover wrongly erased (from the iCloud) emails? I'm in panic cos, in doing that I also erased (din't know that as possible) my emails in my iPhone and iPad….

    Is it possible to recover wrongly erased (from the iCloud) emails? I'm in panic cos, in doing that I also erased (din't know that as possible) my emails in my iPhone and iPad….

  • Is it possible to show a presentation from the original iPad via wireless on an older projector with no HDMI input?

    is it possible to show a presentation from the original iPad via wireless on an older projector with no HDMI input? If so, what equipment is needed?

    The ipad not support wireless projector yet.
    The workaround is you are using computer that connected wirelessly [needs 2 wireless adapter] / via cable to projector and connected also to the wireless router.
    You are controlling the computer via wireless connected to the router using remote desktop app like splashtop, teamviewer, logmein, vnc, etc. You must set the remote desktop port and app at the computer too as ipad app support.

  • Is it possible to only install Color from the FCS3 suite?

    Is it possible to only install Color from the FCS3 suite? If so, what is the correct procedure?
    thanks

    I'm not sure whether you can install it on its own or whether you will need FCP as well.
    Open the installer, go through it and you will come to a page where every app and its media is listed.
    Deselect everything except Color and continue with the installation.
    If it refuses you will have to go back and select FCP as well.

  • Is it possible to exclude single contacts from the mute? For example: I want to hear when I recieve an SMS alert even if I mute my iPhone 4.

    Is it possible to exclude single contacts from the mute? For example: I want to hear when I recieve an SMS alert even if I mute my iPhone 4 (I am a fireman).

    No iPhone apps have access to the necessary API's to do so...they're all sandboxed.

Maybe you are looking for

  • Component video

    Can the Ipad Air output video to component video inputs.  All Ipads with 30 pin adapters are able to do this using the 30 pin to Red/White/Yellow cable Apple sells.  I have the USB that is part of the cable plugged into a power block but I do not thi

  • HT4168 audio or video files in ePub document?

    I'd like to know if we can insert audio or video files to Pages that will export to ePub format? Thanks!

  • Links in Pages

    When I click on a link it opens, but the Pages document closes.  Word doesn't do this.  I think it's probably a simple fix, but I don't know to do it.  How do I keep pages open after clicking on a link that opens in Safari?

  • HT202305 how to restart blocked outbound emails

    Outbound eMails blocked due to exceeding daily limit. How to get that email address working again 3 days later?

  • Table hierarchy

    I have user which consists of 150 tables. I want to hierarchical list of tables in such as way that referential tables will be displayed first then base tables display. e.g. Dept and Emp table. Emp(dept_id) references to Dept(dept_id) So I should dis