I run into an infinite loop when I try and use this print method

Hi,
I have the following class. If i run it in stand alone, everything works out great. However, if I call it from a much larger application (which is why I have built this class), I run into an infinite loop. I have no idea why, but I have pinpointed it to the line: tableView.getTableHeader().paint(g2);
Any help is greatly appreciated. I have been tryin to figure this out for a week now, and I havent gotten anywhere. It makes no sense to me, since this works as a standalone application, but if i put a method similar to the main() inside a much larger application, I end up with an inifinite loop.
Thanks again!
import javax.swing.table.AbstractTableModel;
import javax.swing.*;
import java.awt.print.*;
import java.awt.*;
import java.util.Iterator;
import java.util.ArrayList;
public class printTableTest implements Printable, Pageable {
     private PageFormat pf;
     private String[] headers = { "Heading 1", "Heading 2", "Heading 3"};
     private ArrayList<Object[][]> data = new ArrayList<Object[][]>();
     public printTableTest(PageFormat format) {
          this.pf = format;
                                           this.setObjects();
     public int getNumberOfPages() {
        return 1;
    public PageFormat getPageFormat(int pageIndex) throws IndexOutOfBoundsException {
        return pf;
     public void setObjects() {
          for(int x=0; x < 3; x++) {
               int ndx = 0;
               Object[][] tempData = new Object[2][3               for (; ndx < 2 ; ) {
                    tempData[ndx] = new Object[] { "col 1: " + x, "col 2: " + x, "col 3: " + x };
                    ndx++;
               data.add(tempData);
    public Printable getPrintable(int pageIndex) throws IndexOutOfBoundsException {
        return this;
     public int print(Graphics g, PageFormat format, int pageIndex) throws PrinterException {
          JFrame frame = null;
          JTable tableView = null;                                                       System.err.println("here");
          Graphics2D g2 = (Graphics2D) g;
          //Object[][] data = new Object[3][3];
          g2.setColor(Color.black);
          g2.translate(format.getImageableX() + 72, format.getImageableY() + 72);
          for(int x=0; x < data.size(); x++) {
               tableView = new JTable(new PrintTableModel(headers, data.get(x)));
               frame = new JFrame();
               JScrollPane scrollpane = new JScrollPane(tableView);
               scrollpane.setPreferredSize(new Dimension(300, 80));
               frame.getContentPane().setLayout(new BorderLayout());
               frame.getContentPane().add(BorderLayout.CENTER,scrollpane);
               frame.pack();
               tableView.paint(g2);
               g2.translate(0, - tableView.getTableHeader().getHeight());
               tableView.getTableHeader().paint(g2);
               g2.translate(0, format.getImageableHeight()/3);
          return Printable.PAGE_EXISTS;
     public static void main(String args[]) {
         PrinterJob printerJob = PrinterJob.getPrinterJob();
          printTableTest pp = new printTableTest( printerJob.defaultPage());
          printerJob.setPageable(pp);
          boolean doPrint = printerJob.printDialog();
          if (doPrint) {
               try {
                    printerJob.print();
               } catch (PrinterException exception) {
                    System.err.println("Printing error: " + exception);
         System.exit(0);
     private class PrintTableModel extends AbstractTableModel {
          private Object[][] data = null;
          private String[] headers = null;
          public PrintTableModel(String[] headers, Object[][] data) {
               this.headers = headers;
               this.data = data;
          public int getColumnCount() { return headers.length; }
          public int getRowCount() { return data.length; }
          public Object getValueAt(int row, int col) { return data[row][col]; }
          public String getColumnName(int column) { return headers[column]; }
          public Class getColumnClass(int col) { return getValueAt(0,col).getClass(); }
          public boolean isCellEditable(int row, int col) { return false; }
          public void setValueAt(Object aValue, int row, int column) { data[row][column] = aValue; }
}

Log the parameters passed to my print method?
The only parameter that would be relevant would be the pageNumber, and I can tell you that it continues to loop. Here is an example of the output:
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
Page: 0
and here is the Thread Trace:
AWT-EventQueue-0@42f prio=6, in group "main", status: WAIT
       wait():-1, Object.java
       wait():474, Object.java
       getNextEvent():345, EventQueue.java
       pumpOneEventForHierarchy():189, EventDispatchThread.java
       pumpEventsForHierarchy():163, EventDispatchThread.java
       pumpEvents():157, EventDispatchThread.java
       pumpEvents():149, EventDispatchThread.java
       run():110, EventDispatchThread.java
AWT-Shutdown@430 prio=5, in group "main", status: WAIT
       wait():-1, Object.java
       wait():474, Object.java
       run():259, AWTAutoShutdown.java
       run():595, Thread.java
Java2D Disposer@2a0 daemon prio=10, in group "main", status: WAIT
       wait():-1, Object.java
       remove():116, ReferenceQueue.java
       remove():132, ReferenceQueue.java
       run():107, Disposer.java
       run():595, Thread.java
AWT-Windows@fc daemon prio=6, in group "main", status: RUNNING
       eventLoop():-1, WToolkit.java
       run():269, WToolkit.java
       run():595, Thread.java
Signal Dispatcher@2a2 daemon prio=10, in group "system", status: RUNNING
Finalizer@2a3 daemon prio=8, in group "system", status: WAIT
       wait():-1, Object.java
       remove():116, ReferenceQueue.java
       remove():132, ReferenceQueue.java
       run():159, Finalizer.java
Reference Handler@2a4 daemon prio=10, in group "system", status: WAIT
       wait():-1, Object.java
       wait():474, Object.java
       run():116, Reference.java
main@1 prio=5, in group "main", status: RUNNING
       print():68, printTableTest.java
       redrawRegion():906, WPathGraphics.java
       printPage():1817, RasterPrinterJob.java
       print():1334, RasterPrinterJob.java
       print():1196, RasterPrinterJob.java
       main():1922, TOLMainFrame.java

Similar Messages

  • My iPad won't let me sign into my Apple ID when I try and download an app it asks for my id and password and when i type it in the iPad displays a message saying cannot connect to iTunes Store. However when i do this on my phone it works perfectly.

    My iPad won't let me sign into my Apple ID when I try and download an app it asks for my id and password and when i type it in the iPad displays a message saying cannot connect to iTunes Store. However when i do this on my phone it works perfectly. Even when i sign in and out.
    Has anyone else had this problem? If so how can I fix this?

    Remember, any purchased item from the itunes store is forever associated with the Apple ID used to buy it.  So when you get prompted for an ID/password and it doesn't accept it, then you are using the wrong ID.
    Go to Settings>iTunes and App Stores, be sure it's logged into the ID you have set on the iphone (since that one seems to be connecting with the right ID).  If you've done this, then you might wait a bit to see if the "cannot connect to .. store" message has to do with internet connections.

  • Everytime i go on Itunes it tells me i have to restore my ipod but everytime i do, it just tells me to do it again? When i try and use my ipod it just has a connect to itunes sign and nothing else, it wont work at all?

    Everytime i go on Itunes it tells me i have to restore my ipod but everytime i do, it just tells me to do it again? When i try and use my ipod it just has a connect to itunes sign and nothing else, it wont work at all?
    I updated itunes and everything but nothings working and i just can't figure it out?
    Everytime i restore the stupid thing, it never pops up in my itunes again like its supposed to!

    Loop
    Maybe:
    Restore loop (being prompted to restore again after a restore successfully completes)
    Troubleshoot your USB connection. If the issue persists, out-of-date or incorrectly configured third-party security software may be causing this issue. Please follow Troubleshooting security software issues. .
    Next try placing in DFU mode and then restoring.
    How to put iPod touch / iPhone into DFU mode « Karthik's scribblings
    Then try restoring on another computer.
    Last, make an appointment at the Genius Bar of an Apple store.
    Apple Retail Store - Genius Bar

  • How do I erase my hard drive? My initial operating system was Snow Leopard but I have upgraded to Mavericks OS. My Snow Leopard install disk ejects when I try and use it.

    How do I erase my hard drive? My initial operating system was Snow Leopard but I have upgraded to Mavericks OS. My Snow Leopard install disk ejects when I try and use it.

    Do a backup,  preferable 2 separate ones on 2 drives. Boot to the Recovery Volume (command - R on a restart or hold down the option/alt key during a restart and select Recovery Volume). Run Disk Utility Verify/Repair and Repair Permissions until you get no errors.  Reformat the drive using Disk Utility/Erase Mac OS Extended (Journaled), then click the Option button and select GUID. Then re-install the OS.
    OS X Recovery
    OS X Recovery (2)
    When you reboot, use Setup Assistant to restore your data.

  • When i try and load this brush pack i bought it says "Because this file is not compatible with this version of Photoshop"

    Ive Restarted photoshop Multiple times and it still Doesnt work im on photoshop cs5 and i havent had this problem in a while but again this is a abr file.

    If this problem still persists please verify that this brush pack is compatible with photoshop cs5-also it would help alot to know these things: if your photoshop is running on a apple operating system or windows  operating system  moreover what version of  operating system. Some other things that could hinder this brush pack from working are its installed incorrectly or in the wrong place also resetting cs5 preferences can help. Last if what you posted originally is true and or accurate-"-when i try and load this brush pack i bought" it says "Because this file is not compatible with this version of Photoshop" Then it is exactly as it states a Brush Pack that will not WORK with CS5.

  • Since upgrading to mavericks my applications crash when i try to use the print dialogue

    since upgrading to mavericks my applications crash when i try to use the print dialogue

    Launch the Console application in any of the following ways:
    ☞ Enter the first few letters of its name into a Spotlight search. Select it in the results (it should be at the top.)
    ☞ In the Finder, select Go ▹ Utilities from the menu bar, or press the key combination shift-command-U. The application is in the folder that opens.
    ☞ Open LaunchPad. Click Utilities, then Console in the icon grid.
    Step 1
    Make sure the title of the Console window is All Messages. If it isn't, select All Messages from the SYSTEM LOG QUERIES menu on the left. If you don't see that menu, select
    View ▹ Show Log List
    from the menu bar.
    Enter the name of the crashed application or process in the Filter text field. Select the messages from the time of the last crash, if any. Copy them to the Clipboard by pressing the key combination command-C. Paste into a reply to this message (command-V).
    When posting a log extract, be selective. In most cases, a few dozen lines are more than enough.
    Please do not indiscriminately dump thousands of lines from the log into this discussion.
    Important: Some private information, such as your name, may appear in the log. Anonymize before posting.
    Step 2
    In the Console window, look under User Diagnostic Reports (not "Diagnostic and Usage Messages") for crash reports related to the crashed process. The report name starts with the name of the process, and ends with ".crash". Select the most recent report and post the entire contents — again, the text, not a screenshot. In the interest of privacy, I suggest that, before posting, you edit out the “Anonymous UUID,” a long string of letters, numbers, and dashes in the header of the report, if it’s present (it may not be.) Please don’t post other kinds of diagnostic report — they're very long and not helpful.

  • MY Ipod touch will say it is connected to the wi fi, but when I try and use the wifi for an app it say there is no internet connection.

    My Ipod touch 4.2 will say it is connected to the wi fi but when I try and use it with an app it says it is not connected to the internet

    - Do other devices successfully connect to the network?
    - Did the iPod successfully connect to this network before?
    - Does the iPod successfully connect to other networks?
    Try:
    - A reset. Nothing is lost
    Reset iPod touch: Hold down the On/Off button and the Home button at the same time for at
    least ten seconds, until the Apple logo appears.
    - Power off and then back on your router
    - Reset network settings: Settings>General>Reset>Reset Network Settings
    -iOS: Troubleshooting Wi-Fi networks and connections

  • TS1702 When I try and use the Kindle app on my touch it keeps telling me to register the kindle. I register it using the account and password I used to get the app but it tells me there is no customer found for the email address and password. help

    When I try and use the Kindle app on my touch it keeps telling me to register the kindle. I register it using the account and password I used to get the app but it tells me there is no customer found for the email address and password. help

    No, it is asking you to register with your Amazon user id and password. Your Apple ID won't work.

  • Firefox crashs when I try to use then printer

    I really didn't see an answer to my issue, looking at the previous Q&A. So, I'll try here. Just starting today, when ever I try and use my printer with firefox, I get a crash report? When I try using the printer in another browser, no problem. I've tried many times today, to use the printer in firefox, to no avail. Again, every time, I get a crash report. Can anyone help? Again, this has never been a problem before with my printer and firefox. Appreciate any help. Thank you.
    Rick

    You're welcome

  • When I talk to Siri she can't hear me and when I try and use my mic on the keyboard it doesn't work. What do I do?

    When I talk to Siri she can't hear me and when I try and use my mic on the keyboard it doesn't work. What do I do?

    Siri seems to not be working for many people right now.  The only thing you can do is wait.

  • I converted a heap of music using 'switch', when i try and add this music to library iTunes will not load it??

    i converted a heap of music using 'switch', now when i try and add this to library itunes will not load???

    Unless the MUST be AAC, try FreeWMAtoMP3Changer: http://www.wma-mp3.com/free-wma-to-mp3-converter/
    The ONLY caveat with it is: You CAN'T drag & drop files on it to open them. You MUST use the browse function to select them. If you drag and drop, it multiplies the output files. A 10 track album will produce 45 converted files.

  • Why does the program crash repeatedly when I try and use Sound Cloud

    When I try an use Firefox and upload to Sound Cloud I get this error message repeatedly. This is the error message
    Description:
    A problem caused this program to stop interacting with Windows.
    Problem signature:
    Problem Event Name: AppHangB1
    Application Name: firefox.exe
    Application Version: 26.0.0.5087
    Application Timestamp: 52a0d273
    Hang Signature: 2480
    Hang Type: 0
    OS Version: 6.1.7600.2.0.0.768.3
    Locale ID: 4105
    Additional Hang Signature 1: 24807c2c6ae5950716c093e6ea3101ec
    Additional Hang Signature 2: d24f
    Additional Hang Signature 3: d24f0b50d76295bae82bda3603c82ab7
    Additional Hang Signature 4: 2480
    Additional Hang Signature 5: 24807c2c6ae5950716c093e6ea3101ec
    Additional Hang Signature 6: d24f
    Additional Hang Signature 7: d24f0b50d76295bae82bda3603c82ab7

    Does the problem occur at the point that you expect a dialog to open to select files, or during the upload process, etc.?
    You might already have tried these things, but just in case:
    (1) To rule out one of your extensions as the culprit, can you reproduce the problem in Firefox's Safe Mode? That's a standard diagnostic tool to bypass interference by extensions (and some custom settings). More info: [[Troubleshoot Firefox issues using Safe Mode]].
    You can restart Firefox in Safe Mode using
    Help > Restart with Add-ons Disabled ''(Flash and other plugins still run)''
    In the dialog, click "Start in Safe Mode" (''not'' Reset)
    Any difference?
    (2) If Firefox lags on multiple sites (not responding, slow scripts), try disabling the protected mode feature of the Flash Player plugin. The following pages provide information on how to disable the feature.
    * Adobe support article under the heading "Last Resort": [http://forums.adobe.com/message/4468493#TemporaryWorkaround Adobe Forums: How do I troubleshoot Flash Player's protected mode for Firefox?]
    * Manual steps: https://support.mozilla.org/questions/968190?page=5#answer-509209
    * Batch file to automate the manual steps: https://support.mozilla.org/questions/982093#answer-518078
    That takes effect after Flash is completely unloaded; you might need to exit and restart Firefox.

  • HT5625 I have reset my apple Id and password however when I try and use it in the App Store it says the password is incorrect.

    I have reset my password however when I try to use the App Store it says the password is incorrect.   Do I have to set up an account in iTunes with a credit card in order to use the App Store?  I did not have to do this in he past.  Thanks

    Try This...
    Close All Open Apps... Sign Out of your Account... Perform a Reset... Try again...
    Reset  ( No Data will be Lost )
    Press and Hold the Sleep/Wake Button and the Home Button at the Same Time...
    Wait for the Apple logo to Appear...
    Usually takes about 15 - 20 Seconds... ( But can take Longer...)
    Release the Buttons...
    Note:
    Anything Downloaded with a Particular Apple ID is tied to that Apple ID and Cannot be Merged or Transferred to a Different Apple ID
    Apple ID FAQs  >  http://support.apple.com/kb/HT5622

  • How to cancel a bpm running into an infinite loop

    Hi all,
    I have a business process in my file to file scenario and I am using a while loop to
    process the messages and it is going into infinite loop.
    Now I have corrected the problem and when I reprocess it ,it is using the same original condition for it again the infinite loop.
    So what I understood is I need to cancel out the previous business process which is running into infinite loop .so can you please help me out how do I stop the message processing (and it is not error status also).i,e the business process before I start the fresh test case.
    Thanks in advance,
    Vengal.

    Hi Vengal,
    You can put a condition inside the loop, and whenever that condition will met, it will exit from the loop.
    First of all declare one integer (Int_temp) under container operation.
    Inside the container operation properties, give the variable name and other info as shown below:
    <u><b>Container Operation</b></u>
    Target -
    > Int_temp
    Operation -
    > Assign
    Expression------> Int_temp
    Operator -
    > +
    Experssion -
    > '1'
    Now inside loop properties you can write the condition as shown below:
    Condition -
    > <b>(Int_temp &#8800; 2)</b> (this is just an example)
    The efect of this condition will be on loop till <b>Int_temp</b> is not equal to 2, as soon as it will become 2, it will exit from the loop.
    above is one simple example, there can be several methods.
    I hope it will help you.
    Regards,
    Sarvesh
    ****Reward Points, if found helpfull.

  • Can anyone figure out why this runs into an infinite loop?

    Hi,
    I have the following class, and if i run it, I encounter an infinite loop. I have pinpointed the problem and it is because of the lines:
    try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            catch (Exception exp) {
                   System.err.println("Failed");
                exp.printStackTrace();
            }Here is the class. Any and all help is greatly appreciated. Thanks!
    package org.aemf.clinical.tol.gui.printing;
    import org.aemf.clinical.tol.model.TOLBion;
    import org.aemf.clinical.tol.model.Range;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.*;
    import java.awt.print.*;
    import java.awt.*;
    import java.util.Iterator;
    import java.util.ArrayList;
    * Created by IntelliJ IDEA.
    * User: arashn
    * Date: Feb 9, 2005
    * Time: 1:26:38 PM
    public class printTableTest implements Printable, Pageable {
         private PageFormat pf;
         private String[] headers = { "Heading 1", "Heading 2", "Heading 3"};
         private java.util.List bions = null;
         private ArrayList<Object[][]> data = new ArrayList<Object[][]>();
         public printTableTest(PageFormat format) {
              this.pf = format;
         public int getNumberOfPages() {
            return 1;
        public PageFormat getPageFormat(int pageIndex) throws IndexOutOfBoundsException {
            return pf;
         public void setBions(java.util.List b) {
              bions = b;
              for(int x=0; x < 3; x++) {
                   //TOLBion bion = (TOLBion) bions.get(x);
                   int ndx = 0;
                   //Object[][] tempData = new Object[bion.getNumRanges()][3];
                   Object[][] tempData = new Object[2][3];
              //     for (Iterator itr = bion.getRanges(); ndx < 2 && itr.hasNext(); ) {
                   for (; ndx < 2 ; ) {
                   // Range range = (Range)itr.next();
                        //tempData[ndx] = new Object[] { new Integer(range.getFrequency()), range.getLowerBound(), range.getUpperBound() };
                        tempData[ndx] = new Object[] { "col 1: " + x, "col 2: " + x, "col 3: " + x };
                        ndx++;
                   data.add(tempData);
        public Printable getPrintable(int pageIndex) throws IndexOutOfBoundsException {
            return this;
         public int print(Graphics g, PageFormat format, int pageIndex) throws PrinterException {
              if(pageIndex > 1) {
                   return Printable.NO_SUCH_PAGE;
                                                                              System.err.println("Page: " + pageIndex);
              JFrame frame = null;
              JTable tableView = null;
              Graphics2D g2 = (Graphics2D) g;
              //Object[][] data = new Object[3][3];
              g2.setColor(Color.black);
              g2.translate(format.getImageableX() + 72, format.getImageableY() + 72);
              for(int x=0; x < data.size(); x++) {
                   tableView = new JTable(new PrintTableModel(headers, data.get(x)));
                   frame = new JFrame();
                   JScrollPane scrollpane = new JScrollPane(tableView);
                   scrollpane.setPreferredSize(new Dimension(300, 80));
                   frame.getContentPane().setLayout(new BorderLayout());
                   frame.getContentPane().add(BorderLayout.CENTER,scrollpane);
                   frame.pack();
                   tableView.paint(g2);
                   g2.translate(0, - tableView.getTableHeader().getHeight());
                   tableView.getTableHeader().paint(g2);
                   g2.translate(0, format.getImageableHeight()/3);
              return Printable.PAGE_EXISTS;
         public static void main(String args[]) {
              PrinterJob printerJob = PrinterJob.getPrinterJob();
              try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            catch (Exception exp) {
                   System.err.println("Failed");
                exp.printStackTrace();
             int INCH = 72;
              double LETTER_WIDTH = 8.5 * INCH;
              double LETTER_HEIGHT = 11 * INCH;
            Paper paper = new Paper();
              int margin = INCH/6; // << set your margins here
              double pageWidth = LETTER_WIDTH - 2 * margin;
              double pageHeigth = LETTER_HEIGHT - 2 * margin;
              paper.setImageableArea(margin, margin, pageWidth, pageHeigth) ;
              PageFormat format = printerJob.defaultPage();
              format.setPaper(paper);
            printTableTest pp = new printTableTest(format);
            pp.setBions(new ArrayList());
              printerJob.setPageable(pp);
              boolean doPrint = printerJob.printDialog();
              if (doPrint) {
                   try {
                        printerJob.print();
                   } catch (PrinterException exception) {
                        System.err.println("Printing error: " + exception);
             System.exit(0);
         private class PrintTableModel extends AbstractTableModel {
              private Object[][] data = null;
              private String[] headers = null;
              public PrintTableModel(String[] headers, Object[][] data) {
                   this.headers = headers;
                   this.data = data;
              public int getColumnCount() { return headers.length; }
              public int getRowCount() { return data.length; }
              public Object getValueAt(int row, int col) { return data[row][col]; }
              public String getColumnName(int column) { return headers[column]; }
              public Class getColumnClass(int col) { return getValueAt(0,col).getClass(); }
              public boolean isCellEditable(int row, int col) { return false; }
              public void setValueAt(Object aValue, int row, int column) { data[row][column] = aValue; }
    }

    I have managed to create an even simpler version which tries to print the same header 3 times. Again, if you remove the setLookAndFeel line, everything works out great.
    import javax.swing.table.*;
    import javax.swing.*;
    import java.awt.print.*;
    import java.awt.*;
    * Created by IntelliJ IDEA.
    * User: arashn
    * Date: Feb 9, 2005
    * Time: 1:26:38 PM
    public class printTableTest implements Printable, Pageable {
         private PageFormat pf;
         public printTableTest(PageFormat format) {
              this.pf = format;
         public int getNumberOfPages() {
            return 1;
        public PageFormat getPageFormat(int pageIndex) throws IndexOutOfBoundsException {
            return pf;
        public Printable getPrintable(int pageIndex) throws IndexOutOfBoundsException {
            return this;
         public int print(Graphics g, PageFormat format, int pageIndex) throws PrinterException {
              if(pageIndex > 1) {
                   return Printable.NO_SUCH_PAGE;
              System.err.println("Printing Page: " + pageIndex);
              Graphics2D g2 = (Graphics2D) g;
              g2.setColor(Color.black);
              g2.translate(format.getImageableX() + 72, format.getImageableY() + 72);
              DefaultTableColumnModel dtcm = new DefaultTableColumnModel();
              TableColumn tc = new TableColumn();
              tc.setHeaderValue("Heading 1");
              dtcm.addColumn(tc);
              tc.setHeaderValue("Heading 2");
              dtcm.addColumn(tc);
              tc.setHeaderValue("Heading 2");
              dtcm.addColumn(tc);
              JTableHeader tableHeader = new JTableHeader(dtcm);
              JScrollPane scrollpane2 = new JScrollPane(tableHeader);
              scrollpane2.setPreferredSize(new Dimension(300, 80));
              JFrame frame2 = new JFrame();
              frame2.getContentPane().add(BorderLayout.NORTH,scrollpane2);
              frame2.pack();
              for(int x=0; x < 3; x++) {                   
                   tableHeader.paint(g2);
                   g2.translate(0, format.getImageableHeight()/3);
              return Printable.PAGE_EXISTS;
         public static void main(String args[]) {
              PrinterJob printerJob = PrinterJob.getPrinterJob();
              try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            catch (Exception exp) {
                   System.err.println("Failed");
                exp.printStackTrace();
             int INCH = 72;
              double LETTER_WIDTH = 8.5 * INCH;
              double LETTER_HEIGHT = 11 * INCH;
            Paper paper = new Paper();
              int margin = INCH/6; // << set your margins here
              double pageWidth = LETTER_WIDTH - 2 * margin;
              double pageHeigth = LETTER_HEIGHT - 2 * margin;
              paper.setImageableArea(margin, margin, pageWidth, pageHeigth) ;
              PageFormat format = printerJob.defaultPage();
              format.setPaper(paper);
            printTableTest pp = new printTableTest(format);
              printerJob.setPageable(pp);
              boolean doPrint = printerJob.printDialog();
              if (doPrint) {
                   try {
                        printerJob.print();
                   } catch (PrinterException exception) {
                        System.err.println("Printing error: " + exception);
             System.exit(0);
    }

Maybe you are looking for