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

Similar Messages

  • Help needed in printing in java

    hello everyone, i m in grave need of a solution of printing a java page. I have a page designed in Java swings which contains mainly labels and textareas. And i need to print this page. The problem is that I have no clue how to go ahead. Cud neone arnd pls help me on this matter asap as this is very urgent. I shall be highly obliged to all the takers on this issue. Please email me at [email protected]
    Thanks and kind regards,
    Rahul.

    http://java.sun.com/docs/books/tutorial/2d/printing/index.html

  • Help needed for print layout action.

    Hello, I have a set of 300 or so photos I need to print at work. I work on a large lazer photographic processor capable of doing 50 inch wide prints by however long I need.  I would like to set up an action to layout these photos on a page so that I dont have to copy and paste each one on a page by hand.
    The photos are all the same size. Basically I want to do what contact sheet automation does however I need it to be the full size of the photos not just thumbnails. Just set a document size and have it layout the photos on it untill they are done then I can rip it and print it from my printer. If anyone could help or point me in the right direction that would be great.

    I would use InDesign for this.
    Make your sheet size, then load the place cursor with as many images that fit on a page.
    now just place the images the way you want them.
    Print.

  • **HELP** Need to print keynote with each slide taking the full page

    I just put a keynote presentation together and saved it as a powerpoint. Now that I am trying to print it, the slide only takes a small portion of the page. I need to make sure the slide fits standard letter size and fits the whole page. I want to print one slide per page and have a presentation tomorrow. please help and thank you

    Welcome to the forums!
    You don't give any detail - what, exactly, you are doing (keystrokes, etc.), which program you're trying to print from (KN or PP), and what your settings are, so I'll guess: you're trying to print from KN. When you try to PRINT, in the window which appears you have checked "Slides with Notes". Those notes, even if there's nothing written there, are probably what's taking away space from the slide on your print-out. Instead, check "Individual Slides" (you should see the results of this reflected in the example print-out on the left: the slide should now take up most of the page, rather than just the upper portion of it). To make your slide even a bit bigger, make sure "Use page margins" (under OPTIONS) is unchecked.
    If I've guessed wrong, or my solution doesn't work, come back with more details.
    Good presentation!

  • Help needed in printing pc to pc (printer) using bluetooth

    I require to create a application in final year in which i have to print from my pc to another persons pc who has a printer attached (both pcs are bluetooth enabled using bluetooth dongles using Microsoft stack)
    Do i have to use java rmi ??
    How do i implement this ?? plz i need help !!!

    Adrian, the GIMP Print drivers might have been
    installed automatically when Tiger was installed on
    your computer. They are for older model printers
    whose own drivers aren't native for Tiger. They
    might interfere with a printer's own driver from the
    printer maker.
    I think you may have supplied a link to the Epson incompatibility before spacesuiter. Could you please refresh my memory. I seem to recall the problem was a color shift that was noted on the higher end Epson printers. I have heard of no other specific problems associated with any manufacturer's drivers and any third party drivers including the Gutenprint drivers. I will say that the Epson drivers seemed flawed. They cannot see my SP 1280 if I have my Epson SC 800 attached with a parallel to USB adapter -- even an Epson adapter. That is not a problem with the Gutenprint drivers. As soon as I unplug the SC 800, the SP 1280 functions fine with the Epson drivers.
    In Adrian's case, it appears to me that there is no provision in the Canon PPD for printing black. This is more than a color shift problem. The PPD for the BJC-2100 included with the Gutenprint drivers does contain provisions for Grayscale and Black(inverted grayscale) printing.
    Matt

  • Help needed in printing   interactive form

    Hi Friends
    I just developed an application  which access  ECC
    can any one guide me to print  the output pdfform
    i have opened result interactive form and placed a print button ...next which script i should use? formcalc  or
    java script..since my application is a java webdynpro .
    can  you give me the piece of code for that..formcalc
    already got the script..but  i dont know the exact java script for  printing.
    plz help me in this issue
    vivek chandra

    Hi Raja
    Thanks for that stuff..very helpful
    i  have 3 inputfields on one of my interactive form
    i was asked to fill those fileds  with predefined data
    so that once the app is run, input form fields should
    dispaly the predefiend values.in wdinit method i could
    do that using wdContext.currentelement.setName("xxx");
    i have 3 fields..three are text fields.from the third field need to eneter the date,its a PO Bapi..i did context binding ..i could drag the input  fields..
    but when iam trying to set predefiend date for the
    3rd field..its not accepting it..since it is of type
    date.. do i need to create any data type for the 3rd field in javadictionary????plz guide me in this issue
    regards
    vivek chandra

  • Help needed with print booklet in indesign

    Help! When I attempt to print a 24 page booklet, indesign does not place my last page opposite my first page, and instead adds multiple blank pages to my document. I have the printer option to print blank pages on and I am using a multiple of four to compose my document. Any advice or guidance is much appreciated!

    You need to ask in InDesign
    The Cloud forum is not about using individual programs
    The Cloud forum is about the Cloud as a delivery & install process
    If you will start at the Forums Index https://forums.adobe.com/welcome
    You will be able to select a forum for the specific Adobe product(s) you use
    Click the "down arrow" symbol on the right (where it says All communities) to open the drop down list and scroll

  • Help needed with printer settings for wired ethernet connection

    I'm hoping someone can help me with a network printing issue. I have a large format color laser printer (Tektronix Phaser) and since moving to OS 10.6 I can't figure out how to configure the printer so that the system sees it. I have a simple wired ethernet network with a couple of Macs and a couple of printers. All devices are connected via a switch. When using earlier OSs I was able to connect to the Phaser using Ethertalk. Obviously this is no longer supported and I can't figure out how to set the printer so the OS can see it. I have lots of options which can be turned on or off and in some cases set up in other ways: Ethertalk, IPX, Netware, TCP/IP, DNS, LPR, HTTP and remote internet printing, I've tried messing with these but the result is always the same--system doesn't see the printer. Currently Ethertalk is on, IPX and Netware are off, TCP/IP is on, DNS and LPR are on, as are AppSocket, HTTP, FTP and remote internet printing. I can change the IP address but no matter what address I've tried I cannot ping the printer. (I'm using a Gutenprint driver for this printer.)
    I don't really know enough about all this to get anywhere and I haven't been able to find help anywhere even from tech friends. Xerox won't help me and neither will Apple. Any help would be appreciated. I can supply more detail on specifics where necessary. Thanks, Bob

    Old Phaser models may becoming more and more difficult to use, but you can give this a try.
    1. Configure the printer via front panel to use TCP/IP and enable DHCP if it's supported. If not then you will need to configure an IP address for the printer together with your local network's mask, and gateway IP address. Except for the first the others will be provided by opening Network preferences to see what those settings are. The printer's IP address needs to be set somewhere within the range of IP addresses your router provides locally.
    2. You need the PPD file required for your printer. If you have the Phaser driver installer you can use it to install the PPD or you can extract the specific PPD from the installer package. This part is tricky because I don't know where you may find the driver now if you don't have the installer. The older installers can be accessed through the Finder by selecting the package then CTRL- or RIGHT-click and select Show Package Contents from the contextual menu. You can then rummage through the package to search for the PPD for your printer. Then navigate to the /Library/Printers/PPD/Contents/Resources/ folder and drop the PPD file inside.
    3. Open Print & Fax preferences and click on Add [+] to add a new printer. Click on the IP icon in the toolbar. Select Line Printer Daemon - LPD from the Protocol drop down menu. Input the IP address you assigned the printer in the Address field. You can file in the optional fields that follow. Then from the Print Using drop down menu locate the listing for your printer and select it.

  • Help Needed on Printing

    Hello im a very new junior sd consultant and I have gotten my first issue ticket which I need to try and resolve. Basically, the client has an issue when they want to print the 1.Sales Return document and its 2.Delivery document. they have to keep manually choosing the printer. How can I configure the printer settings for the returns document and its delivery so that for each new sales return document the default printer is already chosen and all they have to do is press enter for example and it prints.
    The current scenerio is that for example, sales return document 000000001. In va02 on the initial screen if you go to sales document, then issue output to. I get this popup when I do those steps "No output has been selected for printing". The client then has to go and assign the printer manually for each document which takes up too much time. How can the printer be assigned by default to that document type?
    Thanks in advance

    Hi Muhammad,
    Please maintain the condition records to that output condition types in VV11 transaction for sales orders and VV21 for delivery document output.
    In condition record itself you can maintain the printer.
    If you maintain the data in the condition record output will come automatically while creating order or while creating delivery.
    I hope it will help you,
    Regards,
    Murali.
    Edited by: Murali Mohan.Tallapaneni on Jul 8, 2008 10:24 AM

  • Help needed in Print List Archiving

    Hi Experts,
    I have archiuved the Print or Spool List and I am able to see that in the OADR Transaction.
    While tring to open document from storage I am getting this error : <b>"Error calling application via OLE ALVIEWER.APP"</b>.
    What is the cause of this error. Please help in rectifying it.
    Regards,
    Arul Jothi. A.

    Hi Arul,
    The message shows that the IXOS Viewer was not being installed in your machine.
    You may request the IXOS Viewer installer from OpenText directly. Or another workaround is to change the printlist display using SAPGUI from TA OAA3. But is might not be a good idea as SAPGUI only allowed to display upto certain number of pages only.

  • Help - need to print borderless 8x10

    I am trying to print a borderless 8x10 pic from my iMac to my Canon i900d printer. I've done it before, but it's been awhile and now every time I try to print I get a 2mm border all around the picture. Again, I want the pic to be borderless, so any help would be greatly appreciated. Thanks.
    Michael

    Welcome to the forums!
    You don't give any detail - what, exactly, you are doing (keystrokes, etc.), which program you're trying to print from (KN or PP), and what your settings are, so I'll guess: you're trying to print from KN. When you try to PRINT, in the window which appears you have checked "Slides with Notes". Those notes, even if there's nothing written there, are probably what's taking away space from the slide on your print-out. Instead, check "Individual Slides" (you should see the results of this reflected in the example print-out on the left: the slide should now take up most of the page, rather than just the upper portion of it). To make your slide even a bit bigger, make sure "Use page margins" (under OPTIONS) is unchecked.
    If I've guessed wrong, or my solution doesn't work, come back with more details.
    Good presentation!

  • Help needed in Printing

    Dear All,
    I am a new switcher to Mac and I have problems printing from Tiger. My printer is a old model Canon BJC2100SP which Tiger have pre-installed its latest driver. However, I couldn't ask it to print black as it will prompt me that the printer couldn't print black. This issue was not surfaced when I tried to print from Windows. Any one can please help me on this?
    Thanks!
    Adrian

    Adrian, the GIMP Print drivers might have been
    installed automatically when Tiger was installed on
    your computer. They are for older model printers
    whose own drivers aren't native for Tiger. They
    might interfere with a printer's own driver from the
    printer maker.
    I think you may have supplied a link to the Epson incompatibility before spacesuiter. Could you please refresh my memory. I seem to recall the problem was a color shift that was noted on the higher end Epson printers. I have heard of no other specific problems associated with any manufacturer's drivers and any third party drivers including the Gutenprint drivers. I will say that the Epson drivers seemed flawed. They cannot see my SP 1280 if I have my Epson SC 800 attached with a parallel to USB adapter -- even an Epson adapter. That is not a problem with the Gutenprint drivers. As soon as I unplug the SC 800, the SP 1280 functions fine with the Epson drivers.
    In Adrian's case, it appears to me that there is no provision in the Canon PPD for printing black. This is more than a color shift problem. The PPD for the BJC-2100 included with the Gutenprint drivers does contain provisions for Grayscale and Black(inverted grayscale) printing.
    Matt

  • Help needed on clearing concept regarding javax.swing.Timer.

    Hello,
    I am not able to understand the concept of Timer. Say suppose
    1) i extend JFrame and create my own frame object
    2) i extend JPanel and create my own panel object
    3) in frame object's constructor i create a panel's object
    4) in panel object's constructor i create a Timer class's object and perform slideshow
    5) after some time ( say when index reaches to 5 i stop timer using timerObj.kill() )
    6) when this timer stops i want the panel object to be removed from frame. This means i need
    to write some code in frame object's constructor that will wait till the timer is running and when it is stopped i would say remove(panelObject). But how to do this??
    Thanks in advance ! :)

    no i don't want to remove the panel within the statement that cancels the timer because basically i want to lot more things also like performing some other kind of animation etc. How can i remove from withing frame's constructor only?i tried the following things :-
    try{
                Thread.currentThread().join();
    catch(InterruptedException ex){           
    while(panelObj.tmObj.isRunning()){
                try{
                    Thread.currentThread().sleep(1000);
                catch(InterruptedException ex){
            }but none of them seems to work. When i write either of the above code nothing happens. Even the window does not appear :(
    Edited by: Salman4u on Mar 31, 2009 9:07 PM

  • Set-up help needed to print from HPJ4580 via Time Machine

    This should work but I can't seem to make it!
    My HPJ4580 prints fine directly from my MacBook Pro but when I go through the steps to connect and print using the USB connection on the Time Capsule (so my husband and I can both print wirelessly) the printer is not found.
    Any ideas on what I'm doing wrong??
    THANKS!

    OK, so between your helpful prompts and my brain finally operating more satisfactorily I have sorted it.
    Turns out I hadn't selected the proper printer driver - I just selected what looked like the right printer name, which of course was the one I had used from when the printer was connected directly to my computer, hence the wrong location (my MacBook Pro).
    I fixed that by clicking the + button on the bottom left of the list and added the printer again but this time with "Kind' being Bonjour so that it now appears in the available printer list with Time Machine identified as the location.
    Et voila... fully operational!
    Thanks for nudging me along.

  • Help needed with Printer Friendly template.

    Hi
    I know there loads of posts on here about "Printer Friendly" Templates which are far from being printer friendly. My problem is that most of my reports are very wide and therefore if you print it you loss the right hand side of the report even if you change the page layout.
    Any Ideas or working examples of getting my reports onto a page without it been cut off?

    Can anybody help me?

Maybe you are looking for