PrinterJob.lookupPrintServices() returns no PrintServices on Solaris 10

I am using a third-party PDF Java print API that uses the Java Print API. The API is used in a WebLogic 10.2 server runtime environment. My problem is that after the server has been running for a day or so, the API is no longer able to see the printers that are set up on a local print server. Issuing lpstat -a from the command line returns all of the printers as does a simple java app that I run from the command line. I have written a simple JSP page to dump out the available PrintServices so I can check to see what's available in the server runtime environment and after a day or so there are none.
The application runs in a cluster and the PrintServices show up just fine on one of the nodes, but the second node is the one that always has a problem. It's not making a lot of sense at this point but any insight into what would cause PrintServices to suddenly become unnoticed by the Java Print API in runtime would be very helpful!
Here is the code from the JSP that checks for the PrintServices:
Available Printers:<br/>
*<ul>*
*<%*
*// List printers*
javax.print.PrintService [] ps = java.awt.print.PrinterJob.lookupPrintServices();
for (int count = 0; count < ps.length; ++count)
*%>*
*<li><b><%=ps [count].getName()%></b> (PrintService class: <%=ps [count].getClass().getName()%>)</li>*
*<%*
*%>*
*</ul>*

Thanks fro the reply.
The system is a T2000(sparc). This server provides CDE desktop to 200s users and is running Citrix Presentation Server. I guess Citirx has its own X server? because I found the xsun process when I checked another sparc server not running Citrix Presentation Server:
# ps -ef|grep -i xsun |grep -v grep
root 682 671 1 Nov 27 ? 2:13 /usr/openwin/bin/Xsun :0 -defdepth 24 -nobanner -auth /var/dt/A:0-xNa4tb
My another question is why the:
/var/svc/manifest/application/x11/x11-server.xml
is not imported to SMF like xfs is?
regards,
Alex

Similar Messages

  • PrinterJob.lookupPrintServices() issues

    We deploy and run JBoss 5.1.0GA on windows 2003.The JBoss is running as window service.
    On the machine, we configure two printers:
    1. network printer
    2. a shared printer on another Window XP machine.
    PrintService[] printServices = PrinterJob.lookupPrintServices();
    The result did not include the shared printer, but the network printer only.
    Outside jboss on the same Windows 2003 machine,
    PrinterJob.lookupPrintServices()
    returns the two printers correctly.
    We post a thread on JBoss forum:
    http://community.jboss.org/message/8748#8748
    and got a reply: JBoss does nothing with printing.
    Thanks for help.
    Dave

    If you are using Linux (and probably other unices) you have to grant read/write-Permissions to /tmp in .java.policy.
    line:
    permission java.io.FilePermission "/tmp/*", "read,write";
    Wolfgang

  • PrinterJob.lookupPrintServices long wait

    Hi everyone,
    I have an applet which load all printers to choose one. In some case, method PrintService[] service = PrinterJob.lookupPrintServices(); take 5 minutes to return a result !
    I've just got one local printer... is anyone have a solution ?
    (same problem with jre 5 or 6)
    Thanks a lot

    I ordered an Extreme Base Station and custom configured MacPro with X1900 XT, BT and Airport card both on 7 August... the Base Station shipped 9 August and just arrived, and the MacPro shipped on 14-August as is still in transit (takes a few days longer to get to Canada).
    Peter O.
    Message was edited by: PeterO2

  • Weblogic 10.3 ---- PrintService class is not finding printers

    Hi folks,
    Am facing an issue in Weblogic 10.3. I have deployed my application which prints the pdf files.
    When i am getting print services available in my machine using
    *PrintService[] printService =
    PrinterJob.lookupPrintServices(); *
    its returning printService.length as *0*.
    But the same application is working fine in other environments like Oracle Soa Suite 10.1.3.3 and Jdeveloper 10.1.3.3.
    Can anybody please suggest on this.
    Please find the Sample Code:
    import java.awt.print.PrinterJob;
    import javax.print.PrintService;
    import org.pdfbox.pdmodel.PDDocument;
    public class PrintPdf {
    public void print(String printerName, String pdfFile) {
    PDDocument document = null;
    try {
    document = PDDocument.load(pdfFile);
    PrinterJob printJob = PrinterJob.getPrinterJob();
    boolean printerFound = false;
    PrintService[] printService = PrinterJob.lookupPrintServices();
    System.out.println("printService length: " + printService.length); //* printService.length is returning 0 *
    for (int i = 0; i < printService.length; i++) {
    System.out.println(i + "==> printService Name: " +
    printService.getName());
    if (printService[i].getName().indexOf(printerName) != -1) {
    printJob.setPrintService(printService[i]);
    printerFound = true;
    System.out.println("Got Printer");
    if (!printerFound) {
    System.out.println("Printer Not found");
    } else {
    printJob.setPageable(document);
    printJob.print();
    System.out.println("Print Successfull");
    } catch (Exception e) {
    e.printStackTrace();

    Thanks for your help.
    When i created a work manager from Deployments -> Configuration -> Workload -> New and the new Work Manager appears in the Application-Scoped Work Managers table. But was not able to see that in Monitering -> Workload Work managers table. Why is that so?
    Regards,
    Smita

  • ViewersSDK on Solaris-java.lang.UnsatisfiedLinkError:getDefaultPrinterName

    I am developing a web application that uses the Viewers SDK to display reports interactively. My application runs fine on a windows, but the following exception is thrown if I deploy it to Solaris:
    com.crystaldecisions.sdk.occa.report.lib.ReportSDKException: getDefaultPrinterName---- Error code:-2147467259 Error code name:failed
            at com.businessobjects.reports.sdk.JRCCommunicationAdapter.<init>(Unknown Source)
            at com.businessobjects.sdk.erom.jrc.a.<init>(Unknown Source)
            at com.businessobjects.sdk.erom.jrc.ReportAgentFactory.createAgent(Unknown Source)
            at com.crystaldecisions.proxy.remoteagent.RemoteAgent$a.<init>(Unknown Source)
            at com.crystaldecisions.proxy.remoteagent.RemoteAgent.a(Unknown Source)
            at com.crystaldecisions.proxy.remoteagent.RemoteAgent.a(Unknown Source)
            at com.crystaldecisions.sdk.occa.report.application.ClientDocument.if(Unknown Source)
            at com.crystaldecisions.sdk.occa.report.application.ClientDocument.open(Unknown Source)
    Caused by: java.lang.UnsatisfiedLinkError: getDefaultPrinterName
            at sun.print.Win32PrintServiceLookup.getDefaultPrinterName(Native Method)
            at sun.print.Win32PrintServiceLookup.getDefaultPrintService(Win32PrintServiceLookup.java:219)
            at sun.print.Win32PrintServiceLookup.getPrintServices(Win32PrintServiceLookup.java:81)
            at sun.print.Win32PrintServiceLookup.getPrintServices(Win32PrintServiceLookup.java:178)
            at javax.print.PrintServiceLookup.getServices(PrintServiceLookup.java:359)
            at javax.print.PrintServiceLookup.lookupPrintServices(PrintServiceLookup.java:105)
            at java.awt.print.PrinterJob.lookupPrintServices(PrinterJob.java:80)
            at com.crystaldecisions.reports.common.j.l(Unknown Source)
            at com.crystaldecisions.reports.common.h.n(Unknown Source)
            at com.crystaldecisions.reports.common.h.i(Unknown Source)
            at com.crystaldecisions.reports.common.Printer.a(Unknown Source)
            at com.businessobjects.reports.reportconverter.v12.d.d(Unknown Source)
            at com.businessobjects.reports.reportconverter.v12.d.m(Unknown Source)
            at com.businessobjects.reports.reportconverter.v12.f.if(Unknown Source)
    On my code I am not even attempting to print anything, just open a report, like this:
    ReportClientDocument reportClientDocument = new ReportClientDocument();
    reportClientDocument.open("report.rpt" 0);
    Any ideas what could be causing this? I am using the latest viewers SDK on java 1.5.0_12, Solaris 10 on Intel.
    Thanks,
    Artur

    The Crystal Reports SDKs require loading the printer information since it uses the printer driver for report formatting. 
    It needs to do so - since only printers have the resolution required on computers to allow for fine resolution (default screen resolution leads to poor results).
    Note that the exception is being thrown by the Java JVM:
    sun.print.Win32PrintServiceLookup.getDefaultPrinterName(Native Method)
    That's whacked, since on Solaris it should never be calling the Win32 version of the PrintServiceLookup.
    Something strange is going on with your Java deployment on Solaris.
    The Java PrintServer initialization is once only - are there anything in your app that explicitly refers to the Win32 version?
    Sincerely,
    Ted Ueda

  • LookupPrintservices() gives default printer name alone...

    Hello,
    There are four printers in the network..operating system is LINUX ..when i run the program its showing only the default printer.
    If i restart the cups service ,then its showing all the options.Why is it
    so....
    So each time when i open the application ,i have to restart the cups..Is this is right way?
    Is there is any other optimistic way to show the printer options.
    Following code
    public static void main(String arg[])
         PrintService[] services = PrinterJob.lookupPrintServices();
         for(int i = 0 ;i < services.length;i++) {
         System.out.println(i+":"+services.getName());
    PrinterJob printerJob = PrinterJob.getPrinterJob();
         if (printerJob.printDialog())
         System.out.println("Printer is There... ");
    PrintService service = printerJob.getPrintService();
         System.out.println("printer Name = " +printerJob.getPrintService().getName());
    Please help me to solve this....Urgent!!!!!!!!!!!!!!!
    Message was edited by:
    rithi_megaa

    OK now it really doesn't make sense. Your code is exporting which has nothing to do with printing from the viewer...
    So, create your own Print Button and handle the file name yourself then you can call it anything you want and it gets printed from the export file name. If that third party PDF printer driver has an API available then you could populate the name there.
    Use your line of code: FileDest.DiskFileName = TextBox2.Text.ToString + " - Postage Report.pdf"
    to set the file name for that PDF Printer.
    Sorry it's really not clear what you are trying to do...
    Don

  • Java PrintService printing Chinese/Japanese characters output is garbled.

    Hi Java Gurus,
    I have been spending the whole day trying to make our text printing application able to print non-western Characters (e.g. Chinese and Japanese) as part of our requirements. But I am constantly getting garbled output when I print a UTF-8 formatted text file containing Chinese characters. I've been trying to switch the DocFlavor types (e.g. byte array in UTF 8, input stream auto sense, UT8-8, etc) but I couldn't simply make it work.
    Here is our test method:
         public void testPrintText(String fileName) throws Exception {
              FileInputStream textStream = new FileInputStream(fileName);
              File file = new File(fileName);
              String fileContent = FileUtils.readFileToString(file);
              DocFlavor flavor = DocFlavor.BYTE_ARRAY.TEXT_PLAIN_UTF_8;
              //DocFlavor flavor = DocFlavor.READER.TEXT_PLAIN;
              InputStreamReader isr = new InputStreamReader(textStream, "utf-8");
              DocAttributeSet das = new HashDocAttributeSet();
              //System.out.println("host encoding: " + flavor.hostEncoding);
              Doc mydoc = new SimpleDoc(fileContent.getBytes("utf-8"), flavor, das);
              //Doc mydoc = new SimpleDoc(textStream, flavor, das);
              PrintRequestAttributeSet pas = new HashPrintRequestAttributeSet();
              pas.add(new PrinterName("\\\\fsinec\\Canon iR5055 PCL6", null));
              PrintService[] services = PrintServiceLookup.lookupPrintServices(flavor, pas);
              PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
              System.out.println("DEBUG: " + defaultService.getClass().getName());
              if(services.length == 0) {       
                   if(defaultService == null) {
                        //no printer found
                   } else {            
                        //print using default
                        DocPrintJob job = defaultService.createPrintJob();
                        job.print(mydoc, pas);
              } else {        
                   //built in UI for printing you may not use this
                   PrintRequestAttributeSet attSet = new HashPrintRequestAttributeSet();
                   for(int ctr=0; ctr<services.length; ctr++) {
                        PrintService printService = services[ctr];
                        System.out.println("COTS DEBUG: " + defaultService.getClass().getName());
                   //attSet.add();
                   PrintService service = null;
                   if(services.length == 1) {
                        //assume that there is no other printer with the name \\\\fsinec\\Canon iR5055 PCL6
                        //resulting to fetch the printer services to only one (1) element.
                        service = services[0];
                   /* open a dialog box
                   * PrintService service =
                        ServiceUI.printDialog(null, 200, 200, services, defaultService, flavor, attSet);*/
                   if (service != null) {           
                        DocPrintJob job = service.createPrintJob();
                        job.print(mydoc, attSet);
    Please help me on this.
    Thanks.

    This could be of different reeasons...
    1) Make sure your printer is uni-code enabled.
    2) Make sure, your unicode enabled printer is configured in SAP.
    3) make sure, your printer device is supported by SAP. (You can find list of SAP recommended printers in www.service.sap.com)
    4) Check whether the correct device type is used for printing chinese and japanese characters.
    5) Check code pages.
    6) Make sure you use Cyrillic font family, for printing chinese and Japanese characters.
    Regards,
    SaiRam

  • Solaris 9 live upgrade to solaris 10 segmentation fault

    pre-upgrade work:
    apply patch doc 72099
    upgrade live upgrade to solaris 10.
    lucreate-m /:/dev/dsk/c0t1d0s0:ufs -m /var:/dev/dsk/c0t1d0s1:ufs -m /opt:/dev/dsk/c0t1d0s3:ufs -n sol10
    it works well
    oot Environment Is Active Active Can Copy
    Name Complete Now On Reboot Delete Status
    sol9 yes yes yes no -
    sol10 yes no no yes -
    But luupgrade -u -n sol10 -s /sol11
    Validating the contents of the media </sol11>.
    The media is a standard Solaris media.
    The media contains an operating system upgrade image.
    The media contains <Solaris> version <11>.
    Constructing upgrade profile to use.
    Locating the operating system upgrade program.
    Checking for existence of previously scheduled Live Upgrade requests.
    Creating upgrade profile for BE <sol10>.
    Determining packages to install or upgrade for BE <sol10>.
    Performing the operating system upgrade of the BE <sol10>.
    CAUTION: Interrupting this process may leave the boot environment unstable
    or unbootable.
    /usr/sbin/luupgrade&#91;677&#93;: 6549 Segmentation Fault(coredump)
    ERROR: Installation of the packages from this media of the media failed; pfinstall returned these diagnostics:
    The Solaris upgrade of the boot environment <sol10> failed.

    I would break your mirror and do a liveupgrade on the available mirror. Then boot that disk.

  • 4.51 new InitialContext never returns

    4.51 new InitialContext never returns
    When I do a "new InitialContext" in my client test program, it never
    returns
    when run on solaris or linux, it works fine on NT.
    Another symptom of the same problem is that a LIST command of
    weblogic.Admin works
    on NT but never returns on Solaris or Linux.
    VERSION and SHUTDOWN work on NT, Solaris and Linux.
    also note that on linux with ibm 1.1.8 jdk, I completely re-loaded the
    weblogic
    with only the system password changed in the weblogic.properties file
    (just to
    make sure I did not accidently put something in the properties file to
    cause
    the problem)
    here is the some raw data, I do relaize that some of these combinations
    are not certified (none of the Solaris or Linux combinations worked).
    Sun Ultra10 2.5.1 with jdk1.1.8 no service pack
    Sun Ultra10 2.5.1 with jdk1.1.8 service pack 8
    Sun Ultra10 2.5.1 with jdk1.1.7 service pack 8
    Windows NT 4.0 service pack 6a javasoft jdk1.2.2 weblogic service pack 7
    linux (redhat 6.2 with blackdown jdk1.2.2)
    linux (redhat 6.2 with ibm1.1.8 jdk)
    changes to weblogic.properties:
    weblogic.system.password=syspword
    to startup weblogic:
    export PATH=$PATH:/usr/local/jdk118/bin
    export JDK_HOME=/usr/local/jdk118
    export
    CLASSPATH=./classes:./lib/weblogicaux.jar:./myserver/serverclasses
    ./startWebLogic.sh
    code segment from client program:
    static public Context getInitialContext()
    Context returnValue = null;
    Properties p;
    p = new Properties();
    p.put(Context.INITIAL_CONTEXT_FACTORY,
    "weblogic.jndi.TengahInitialContextFactory");
    p.put(Context.PROVIDER_URL,"t3://207.112.33.206:7001");
    try
    System.out.println("getting initial context");
    returnValue = new InitialContext(p);
    System.out.println("got initial context");
    catch (NamingException ex)
    System.out.println("exception");
    System.out.println("NamingException " +
    ex.getMessage())
    ex.printStackTrace();
    catch (Exception ex)
    System.out.println("exception");
    return returnValue;
    results of running the client program:
    getting initial context
    the client program never returns
    check linux version:
    [jack@linux01 test]$ uname -a
    Linux linux01.delfour.com 2.2.14-5.0 #1 Tue Mar 7 20:53:41 EST 2000 i586
    unknown
    check weblogic version on NT:
    [jack@linux01 test]$ java weblogic.Admin t3://207.112.33.203:7001
    VERSION
    WebLogic Build: 4.5.1 Service Pack 7 02/16/2000 15:17:50 #63218
    check weblogic version on linux:
    [jack@linux01 test]$ java weblogic.Admin t3://localhost:7001 VERSION
    WebLogic Build: 4.5.1 09/30/1999 17:41:18 #53704
    test one: linux client to linux server:
    [jack@linux01 test]$ java weblogic.Admin t3://localhost:7001 PING 1 1
    Sending 1 ping of 1 byte.
    RTT = ~741 milliseconds, or ~741 milliseconds/packet
    test two: linux client to linux server:
    [jack@linux01 test]$ java weblogic.Admin t3://localhost:7001 LIST
    weblogic system bogus
    Setting credentials
    An AuthenticationException occurred that prevented access to the given
    name in the naming service. The username/password you supplied is not
    authorized for thi
    s operation.
    test three: linux client to linux server:
    [jack@linux01 test]$ java weblogic.Admin t3://localhost:7001 LIST
    weblogic syste
    m syspword
    Setting credentials
    after 5 minutes, still no response
    test four: linux client to NT server:
    [jack@linux01 test]$ java weblogic.Admin t3://207.112.33.203:7001 LIST
    weblogic system password
    Setting credentials
    Contents of weblogic
    fileSystem:
    weblogic.jndi.toolkit.ReplicatedWLContext:weblogic.jndi.toolkit.WL
    [email protected]:[7001,7001,7002,7002,-1]
    NameBas
    edFailOverHandler (name: weblogic.fileSystem, env:
    weblogic.jndi.Environment@806
    05d5
    ejb:
    weblogic.jndi.toolkit.ReplicatedWLContext:weblogic.jndi.toolkit.WLContext
    [email protected]:[7001,7001,7002,7002,-1]
    NameBasedFailO
    verHandler (name: weblogic.ejb, env: weblogic.jndi.Environment@80605d5
    common:
    weblogic.jndi.toolkit.ReplicatedWLContext:weblogic.jndi.toolkit.WLCont
    [email protected]:[7001,7001,7002,7002,-1]
    NameBasedFa
    ilOverHandler (name: weblogic.common, env:
    weblogic.jndi.Environment@80605d5
    jdbc:
    weblogic.jndi.toolkit.ReplicatedWLContext:weblogic.jndi.toolkit.WLContex
    [email protected]:[7001,7001,7002,7002,-1]
    NameBasedFail
    OverHandler (name: weblogic.jdbc, env: weblogic.jndi.Environment@80605d5
    jts:
    weblogic.jndi.toolkit.ReplicatedWLContext:weblogic.jndi.toolkit.WLContext
    [email protected]:[7001,7001,7002,7002,-1]
    NameBasedFailO
    verHandler (name: weblogic.jts, env: weblogic.jndi.Environment@80605d5
    server:
    weblogic.jndi.toolkit.ReplicatedWLContext:weblogic.jndi.toolkit.WLCont
    [email protected]:[7001,7001,7002,7002,-1]
    NameBasedFa
    ilOverHandler (name: weblogic.server, env:
    weblogic.jndi.Environment@80605d5
    rmi:
    weblogic.jndi.toolkit.ReplicatedWLContext:weblogic.jndi.toolkit.WLContext
    [email protected]:[7001,7001,7002,7002,-1]
    NameBasedFailO
    verHandler (name: weblogic.rmi, env: weblogic.jndi.Environment@80605d5
    jms:
    weblogic.jndi.toolkit.ReplicatedWLContext:weblogic.jndi.toolkit.WLContext
    [email protected]:[7001,7001,7002,7002,-1]
    NameBasedFailO
    verHandler (name: weblogic.jms, env: weblogic.jndi.Environment@80605d5
    jndi:
    weblogic.jndi.toolkit.ReplicatedWLContext:weblogic.jndi.toolkit.WLContex
    [email protected]:[7001,7001,7002,7002,-1]
    NameBasedFail
    OverHandler (name: weblogic.jndi, env: weblogic.jndi.Environment@80605d5
    here is the end of the weblogic traces after a single LIST on linux:
    Sun May 07 09:40:34 EDT 2000:<I> <WebLogicServer> Server loading from
    weblogic.c
    lass.path. EJB redeployment enabled.
    Sun May 07 09:40:44 EDT 2000:<I> <WebLogicServer> Event handler log
    started (reg
    id: 1)
    Sun May 07 09:40:44 EDT 2000:<I> <WebLogicServer> Invoking main-style
    startup we
    blogic.jdbc.common.internal.JdbcStartup
    weblogic.jdbc.common.internal.JdbcStartu
    p
    Sun May 07 09:40:48 EDT 2000:<S> <SSLListenThread> 2 certificate(s):
    fingerprint = 88dae49f1a3122e62e7a94a3dc76fbf0, not before = Tue Oct
    26 15:03:
    00 EDT 1999, not after = Tue Oct 24 15:03:00 EDT 2000, holder = C=US
    SP=Californ
    ia L=San Francisco O=WebLogic CN=weblogic.beasys.com
    [email protected]
    , issuer = C=US SP=California L=San Francisco O=WebLogic OU=Security
    CN=Demonstr
    ation Certificate Authority [email protected] , key = modulus =
    65 byte
    Bignum
    value=00959b5668811e78a28a018631455f5bd4f51b0e3e77b79dcb7a4c67c31a8f94b0
    4bce347b731121da27918dd36bce8f1f0b77cd7944ecbd3d517baa3a83dcce8b,
    exponent = 3 b
    yte Bignum value=010001
    fingerprint = f1c530f7211410a2220c7e9d3152b496, not before = Tue Oct
    26 14:18:
    53 EDT 1999, not after = Wed Oct 25 14:18:53 EDT 2000, holder = C=US
    SP=Californ
    ia L=San Francisco O=WebLogic OU=Security CN=Demonstration Certificate
    Authority
    [email protected] , issuer = C=US SP=California L=San
    Francisco O=WebL
    ogic OU=Security CN=Demonstration Certificate Authority
    [email protected]
    om , key = modulus = 65 byte Bignum
    value=00b6743b62ce13992324b18d8061d24457ff90
    5b7e8aaceef6bef802b6f8a1e176f9791d571f14df79e9dd40f1f8e83e9e41048f05f931fe07dc06
    2f19ac20fa93, exponent = 3 byte Bignum value=010001
    Sun May 07 09:40:48 EDT 2000:<I> <SSLListenThread> Using exportable
    strength
    SSL
    Sun May 07 09:40:50 EDT 2000:<I> <JMS> Beginning startup process
    Sun May 07 09:40:50 EDT 2000:<I> <JMS> Init JMS Security
    Sun May 07 09:40:51 EDT 2000:<I> <JMS> Startup process complete. JMS is
    active
    Sun May 07 09:40:51 EDT 2000:<I> <WebLogicServer> Invoking main-style
    startup RM
    I Registry weblogic.rmi.internal.RegistryImpl
    Sun May 07 09:40:51 EDT 2000:<I> <RMI> Registry started
    Sun May 07 09:40:52 EDT 2000:<I> <EJB> 0 EJBs were deployed using .ser
    files.
    Sun May 07 09:40:52 EDT 2000:<I> <EJB> 0 EJBs were deployed using .jar
    files.
    Sun May 07 09:40:53 EDT 2000:<I> <ZAC> ZAC ACLs initialized
    Sun May 07 09:40:53 EDT 2000:<I> <ZAC> ZAC packages stored in local
    directory ex
    ports
    Sun May 07 09:40:54 EDT 2000:<I> <ListenThread> Listening on port: 7001
    Sun May 07 09:40:57 EDT 2000:<I> <SSLListenThread> Listening on port:
    7002
    Sun May 07 09:40:58 EDT 2000:<I> <WebLogicServer> WebLogic Server
    started
    Sun May 07 09:41:09 EDT 2000:<I> <ListenThread> Adding address:
    linux01.delfour.
    com/207.112.33.206 to licensed client list
    Sun May 07 09:41:12 EDT 2000:<I> <RJVM> Creating connection to
    localhost/127.0.0
    .1 -1260680115049870327
    I hope someone can shed some light on this...
    - Rob (jack) Lapensee

    It looks like you are modifying the object you are iterating over while you are iterating... not good. Say your gp only had one element, a LINE_TO. It will run through and call another LINE_TO in the switch, thus when it comes back to the while, there is a newly added point to interpret, so the iterator will never finish. Usually, most components throw a ConcurrentModificationException when this happens for this type of case. I'm not sure why the PathIterator doesn't.
    In short, use a different reference in the loop then the one you are iterating over.
    -JBoeing

  • Print JTable with Multiple pages and rows

    I took the printing example at http://java.sun.com/developer/onlineTraining/Programming/JDCBook/advprint.html#pe and modified it a bit to include the following:
    1) To Print Multiple pages
    2) To wrap lines that is too long for the column
    3) To print with a more proffesional style, so that it doesn't look like a screen capture is printed
    4) To align the numbers to the right and center column headings
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.print.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.Dimension;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    import java.text.*;
    public class Report implements Printable
         private final int LEFT_ALIGN = -1;
         private final int CENTER_ALIGN = 0;
         private final int RIGHT_ALIGN = 1;
         private JFrame frame;
         private JTable tableView;
         private String lastPrintDate;
         private Font defaultFont;
         private Font headerFont;
         private Font footerFont;
         private int headerHeight;
         private int footerHeight;
         private int cellBuffer = 5;
         private boolean first_pass;
         private ArrayList pages;
         public Report()
              frame = new JFrame("Sales Report");
              frame.addWindowListener(new WindowAdapter()
                   public void windowClosing(WindowEvent e)
                        System.exit(0);
              final String[] headers =
                   "ID",
                   "Description",
                   "open price",
                   "latest price",
                   "End Date",
                   "Quantity"
              int count = 0;
              final Object[][] data =
                   {new Integer(count++), "Box of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of BirosBox of Biros ppppppppppppppp", "1.00", "4.99", new Date(), new Integer(200000)},
                   {new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++), "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++), "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++), "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++), "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++), "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++), "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++), "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++),  "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++),  "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)},
                   {new Integer(count++),  "Blue Biro", "0.10", "0.14", new Date(), new Integer(1)},
                   {new Integer(count++),  "legal pad", "1.00", "2.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "tape", "1.00", "1.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "stapler", "4.00", "4.49", new Date(), new Integer(1)},
                   {new Integer(count++),  "Box of Biros", "1.00", "4.99", new Date(), new Integer(2)}
              TableModel dataModel = new AbstractTableModel()
                   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 (col==1);
                   public void setValueAt(Object aValue, int row, int column)
                        data[row][column] = aValue;
              tableView = new JTable(dataModel);
              JScrollPane scrollpane = new JScrollPane(tableView);
              scrollpane.setPreferredSize(new Dimension(500, 80));
              frame.getContentPane().setLayout(new BorderLayout());
              frame.getContentPane().add(BorderLayout.CENTER,scrollpane);
              frame.pack();
              JButton printButton= new JButton();
              printButton.setText("print me!");
              frame.getContentPane().add(BorderLayout.SOUTH,printButton);
              // for faster printing turn double buffering off
              RepaintManager.currentManager(frame).setDoubleBufferingEnabled(false);
              printButton.addActionListener( new ActionListener()
                   public void actionPerformed(ActionEvent evt)
                        doPrint();
              frame.setVisible(true);
          * Reset variables before printing
         private void prepareForPrint()
              pages = new ArrayList();
              first_pass = true;
          * Display a print dialog with some hardcoded defaults
          * The print fonts are also hardcoded
         public void doPrint()
              try
                   String jobName = "Java Report";
                   defaultFont = new Font("Arial", Font.PLAIN, 8);
                   footerFont = new Font("Arial", Font.PLAIN, 6);
                   headerFont = new Font("Arial", Font.BOLD, 10);
                   PrinterJob prnJob = PrinterJob.getPrinterJob();
                   prnJob.setPrintable(this);
                   PrintRequestAttributeSet prnSet = new HashPrintRequestAttributeSet();
                   prnSet.add(new Copies(1));
                   prnSet.add(new JobName(jobName, null));
                   prnSet.add(MediaSizeName.ISO_A4);
                   PageFormat pf = prnJob.defaultPage();
                   pf.setOrientation(java.awt.print.PageFormat.PORTRAIT);
                   prnJob.setJobName(jobName);
                   PrintService[] services = PrinterJob.lookupPrintServices();
                   if (services.length > 0)
                        if (prnJob.printDialog(prnSet))
                              * Get print date
                             String dateFormat = "dd/MM/yyyy HH:mm:ss";
                             DateFormat m_DateFormat = new SimpleDateFormat(dateFormat);
                             lastPrintDate = m_DateFormat.format(new Date()).toString();
                             prepareForPrint();
                             prnJob.print(prnSet);
                   else
                        JOptionPane.showMessageDialog(frame, "No Printer was found!!", "Printer Error", JOptionPane.ERROR_MESSAGE);
                        return;
              catch (PrinterException e)
                   e.printStackTrace();
         public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException
               * Check if this is the first time the print method is called for this print action.
               * It is not guaranteed that the print will be called with synchronous pageIndex'es,
               * so we need to calculate the number of pages and which rows appear on which pages.
               * Then the correct page will be printed regardless of which pageIndex is sent through.
              if (first_pass)
                   calcPages(g, pageFormat);
              first_pass = false;
              // Stop printing if the pageIndex is out of range
              if (pageIndex >= pages.size())
                   return NO_SUCH_PAGE;
              Graphics2D     g2 = (Graphics2D) g;
              g2.setColor(Color.black);
              // The footer will be one line at the bottom of the page, cater for this.
              g2.setFont(footerFont);
              footerHeight = g2.getFontMetrics().getHeight() + g2.getFontMetrics().getDescent();
              g2.setFont(defaultFont);
              FontMetrics fontMetrics = g2.getFontMetrics();
              int fontHeight = fontMetrics.getHeight();
              int fontDescent = fontMetrics.getDescent();
              double pageHeight = pageFormat.getImageableHeight() + pageFormat.getImageableY();
              double pageWidth = pageFormat.getImageableWidth();
              double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
              // Shrink or expand the table to fit the page width
              double scale = pageWidth / (tableWidth+ (cellBuffer * tableView.getColumnCount()));
              // Calculate the width in pixels for each column
              double[] columnWidths = new double[tableView.getColumnCount()];
              for(int i = 0; i < tableView.getColumnCount(); i++)
                   columnWidths[i] = (double)tableView.getColumnModel().getColumn(i).getWidth() * scale;
              // Reset the view to the start of the page
              g2.translate(0, 0);
              // Draw a rectangle to see the printable area
              g2.draw3DRect((int)pageFormat.getImageableX(),
                        (int)pageFormat.getImageableY(),
                        (int)pageFormat.getImageableWidth(),
                        (int)pageFormat.getImageableHeight(),
                        false);
              // Calculate the header height
              g2.setFont(headerFont);
              fontMetrics = g2.getFontMetrics();
              // Print the headers and retreive the starting position for the data
              int next_row = printLine(g2, pageFormat, fontMetrics, -1, (int)pageFormat.getImageableY() + fontHeight, columnWidths);
              g2.setFont(defaultFont);
              fontMetrics = g2.getFontMetrics();
              // Start printing the detail
              ArrayList page = (ArrayList)pages.get(pageIndex);
              int start = ((Integer)page.get(0)).intValue();
              int end = ((Integer)page.get(1)).intValue();
              for (int i = start; i <= end; i++)
                   next_row = printLine(g2, pageFormat, fontMetrics, i, next_row, columnWidths);
              // Print the footer
              g2.setFont(footerFont);
              String pageFooter = "Page " + (pageIndex + 1) + " - " + lastPrintDate;
              g2.drawString(pageFooter,
                             (int)pageFormat.getWidth() / 2 - (fontMetrics.stringWidth(pageFooter) / 2),
                             (int)(pageHeight - fontDescent));
              return PAGE_EXISTS;
          * We can't guarantee that the same amount of rows will be displayed on each page,
          * the row heights are dynamic and may wrap onto 2 or more lines.
          * Thus we need to calculate the height of each row and then test how may rows
          * fit on a specific page. eg. Page 1 contains rows 1 to 10, Page 2 contains rows 11 to 15 etc.
         public void calcPages(Graphics g, PageFormat pageFormat) throws PrinterException
              Graphics2D     g2 = (Graphics2D) g;
              g2.setColor(Color.black);
              // The footer will be one line at the bottom of the page, cater for this.
              g2.setFont(footerFont);
              footerHeight = g2.getFontMetrics().getHeight() + g2.getFontMetrics().getDescent();
              g2.setFont(defaultFont);
              FontMetrics fontMetrics = g2.getFontMetrics();
              int fontHeight = fontMetrics.getHeight();
              int fontDescent = fontMetrics.getDescent();
              double pageHeight = pageFormat.getImageableHeight() - fontHeight;
              double pageWidth = pageFormat.getImageableWidth();
              double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
              // Shrink or expand the table to fit the page width
              double scale = pageWidth / (tableWidth+ (cellBuffer * tableView.getColumnCount()));
              // Calculate the width in pixels for each column
              double[] columnWidths = new double[tableView.getColumnCount()];
              for(int i = 0; i < tableView.getColumnCount(); i++)
                   columnWidths[i] = (double)tableView.getColumnModel().getColumn(i).getWidth() * scale;
              // Calculate the header height
              int maxHeight = 0;
              g2.setFont(headerFont);
              fontMetrics = g2.getFontMetrics();
              for (int j = 0; j < tableView.getColumnCount(); j++)
                   String value = tableView.getColumnName(j).toString();
                   int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                   if (numLines > maxHeight)
                        maxHeight = numLines;
              headerHeight = g2.getFontMetrics().getHeight() * maxHeight;
              g2.setFont(defaultFont);
              fontMetrics = g2.getFontMetrics();
              int pageNum = 0;
              int bottom_of_page = (int)(pageFormat.getImageableHeight() + pageFormat.getImageableY()) - footerHeight;
              int prev_row = 0;
              int next_row = (int)pageFormat.getImageableY() + fontHeight + headerHeight;
              int i = 0;
              ArrayList page = new ArrayList();
              page.add(new Integer(0));
              for (i = 0; i < tableView.getRowCount(); i++)
                   maxHeight = 0;
                   for (int j = 0; j < tableView.getColumnCount(); j++)
                        String value = tableView.getValueAt(i, j).toString();
                        int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                        if (numLines > maxHeight)
                             maxHeight = numLines;
                   prev_row = next_row;
                   next_row += (fontHeight * maxHeight);
                   // If we've reached the bottom of the page then set the current page's end row
                   if (next_row > bottom_of_page)
                        page.add(new Integer(i - 1));
                        pages.add(page);
                        page = new ArrayList();
                        page.add(new Integer(i));
                        pageNum++;
                        next_row = (int)pageFormat.getImageableY()
                                       + fontHeight
                                       + ((int)pageFormat.getHeight() * pageNum)
                                       + headerHeight;
                        bottom_of_page = (int)(pageFormat.getImageableHeight()
                                            + pageFormat.getImageableY())
                                            + ((int)pageFormat.getHeight() * pageNum)
                                            - footerHeight;
                        //Include the current row on the next page, because there is no space on this page
                        i--;
              page.add(new Integer(i - 1));
              pages.add(page);
          * Print the headers or a row from the table to the graphics context
          * Return the position of the row following this one
         public int printLine(Graphics2D g2,
                                       PageFormat pageFormat,
                                       FontMetrics fontMetrics,
                                       int rowNum,
                                       int next_row,
                                       double[] columnWidths)
                   throws PrinterException
              int lead = 0;
              int maxHeight = 0;
              for (int j = 0; j < tableView.getColumnCount(); j++)
                   String value = null;
                   int align = LEFT_ALIGN;
                   if (rowNum > -1)
                        Object obj = tableView.getValueAt(rowNum, j);
                        if (obj instanceof Number)
                             align = RIGHT_ALIGN;
                        value = obj.toString();
                   else
                        align = CENTER_ALIGN;
                        value = tableView.getColumnName(j);
                   int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                   if (numLines > maxHeight)
                        maxHeight = numLines;
                   if (fontMetrics.stringWidth(value) < columnWidths[j])
                        // Single line
                        int offset = 0;
                        // Work out the offset from the start of the column to display alignment correctly
                        switch (align)
                             case RIGHT_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)); break;
                             case CENTER_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)) / 2; break;
                             default: offset = 0; break;
                        g2.drawString(value,
                                       lead + (int)(pageFormat.getImageableX() + offset),
                                       next_row);
                   else
                        for(int a = 0; a < numLines; a++)
                             //Multi-Line
                             int x = 0;
                             int width = 0;
                             for(x = 0; x < value.length(); x++)
                                  width += fontMetrics.charWidth(value.charAt(x));
                                  if (width > columnWidths[j])
                                       break;
                             int offset = 0;
                             // Work out the offset from the start of the column to display alignment correctly
                             switch (align)
                                  case RIGHT_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)); break;
                                  case CENTER_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)) / 2; break;
                                  default: offset = 0; break;
                             g2.drawString(value.substring(0, x),
                                            lead + (int)(pageFormat.getImageableX() + offset),
                                            next_row + (fontMetrics.getHeight() * a));                    
                             value = value.substring(x);
                   lead += columnWidths[j] + cellBuffer;
              // Draw a solid line below the row
              g2.draw(new Line2D.Double(pageFormat.getImageableX(),
                             next_row + (fontMetrics.getHeight() * (maxHeight - 1)) + fontMetrics.getDescent(),
                             pageFormat.getImageableY() + pageFormat.getImageableWidth(),
                             next_row + (fontMetrics.getHeight() * (maxHeight - 1)) + fontMetrics.getDescent()));
              // Return the position of the row following this one
              return next_row + (fontMetrics.getHeight() * maxHeight);
         public static void main(String[] args)
              new Report();
    }

    Fixed some bugs and added a title. Just pass in a JTable and the class will do the rest.
    import javax.swing.*;
    import javax.swing.table.*;
    import java.awt.print.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    import java.text.*;
    import java.math.*;
    public class PrintJTable implements Printable
         private final int LEFT_ALIGN = -1;
         private final int CENTER_ALIGN = 0;
         private final int RIGHT_ALIGN = 1;
         private JFrame m_parent;
         private String m_title;
         private JTable tableView;
         private String lastPrintDate;
         private Font defaultFont;
         private Font headerFont;
         private Font footerFont;
         private int headerHeight;
         private int footerHeight;
         private int cellBuffer = 5;
         private boolean first_pass;
         private ArrayList pages;
         public PrintJTable(JFrame parent, JTable table)
              m_parent = parent;
              tableView = table;
              doPrint();
         public PrintJTable(JFrame parent, String title, JTable table)
              m_parent = parent;
              m_title = title;
              tableView = table;
              doPrint();
          * Reset variables before printing
         private void prepareForPrint()
              pages = new ArrayList();
              first_pass = true;
          * Display a print dialog with some hardcoded defaults
          * The print fonts are also hardcoded
         public void doPrint()
              try
                   String jobName = "Java Report";
                   defaultFont = new Font("Arial", Font.PLAIN, 8);
                   footerFont = new Font("Arial", Font.PLAIN, 6);
                   headerFont = new Font("Arial", Font.BOLD, 8);
                   PrinterJob prnJob = PrinterJob.getPrinterJob();
                   prnJob.setPrintable(this);
                   PrintRequestAttributeSet prnSet = new HashPrintRequestAttributeSet();
                   prnSet.add(new Copies(1));
                   prnSet.add(new JobName(jobName, null));
                   prnSet.add(MediaSizeName.ISO_A4);
                   PageFormat pf = prnJob.defaultPage();
                   pf.setOrientation(java.awt.print.PageFormat.PORTRAIT);
                   prnJob.setJobName(jobName);
                   PrintService[] services = PrinterJob.lookupPrintServices();
                   if (services.length > 0)
                        if (prnJob.printDialog(prnSet))
                              * Get print date
                             String dateFormat = "dd/MM/yyyy HH:mm:ss";
                             DateFormat m_DateFormat = new SimpleDateFormat(dateFormat);
                             lastPrintDate = m_DateFormat.format(new Date()).toString();
                             prepareForPrint();
                             prnJob.print(prnSet);
                   else
                        JOptionPane.showMessageDialog(m_parent, "No Printer was found!!", "Printer Error", JOptionPane.ERROR_MESSAGE);
                        return;
              catch (PrinterException e)
                   e.printStackTrace();
         public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException
               * Check if this is the first time the print method is called for this print action.
               * It is not guaranteed that the print will be called with synchronous pageIndex'es,
               * so we need to calculate the number of pages and which rows appear on which pages.
               * Then the correct page will be printed regardless of which pageIndex is sent through.
              if (first_pass)
                   calcPages(g, pageFormat);
              first_pass = false;
              // Stop printing if the pageIndex is out of range
              if (pageIndex >= pages.size())
                   return NO_SUCH_PAGE;
              Graphics2D     g2 = (Graphics2D) g;
              g2.setColor(Color.black);
              // The footer will be one line at the bottom of the page, cater for this.
              g2.setFont(footerFont);
              footerHeight = g2.getFontMetrics().getHeight() + g2.getFontMetrics().getDescent();
              g2.setFont(defaultFont);
              FontMetrics fontMetrics = g2.getFontMetrics();
              int fontHeight = fontMetrics.getHeight();
              int fontDescent = fontMetrics.getDescent();
              double pageHeight = pageFormat.getImageableHeight() + pageFormat.getImageableY();
              double pageWidth = pageFormat.getImageableWidth();
              double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
              // Shrink or expand the table to fit the page width
              double scale = (pageWidth - (cellBuffer * tableView.getColumnCount())) / tableWidth;
              // Calculate the width in pixels for each column
              double[] columnWidths = new double[tableView.getColumnCount()];
              double test = 0;
              for(int i = 0; i < tableView.getColumnCount(); i++)
                   columnWidths[i] = (double)Math.floor(tableView.getColumnModel().getColumn(i).getWidth() * scale);
                   test += columnWidths;
              // Reset the view to the start of the page
              g2.translate(0, 0);
              // Draw a rectangle to see the printable area
              g2.draw3DRect((int)pageFormat.getImageableX(),
                        (int)pageFormat.getImageableY(),
                        (int)pageFormat.getImageableWidth(),
                        (int)pageFormat.getImageableHeight(),
                        false);
              // Calculate the header height
              g2.setFont(headerFont);
              fontMetrics = g2.getFontMetrics();
              // Print the headers and retreive the starting position for the data
              int next_row = (int)pageFormat.getImageableY() + fontMetrics.getHeight();
              if ((m_title != null) && (!m_title.equalsIgnoreCase("")))
                   g2.drawString(m_title,
                                       (int)(pageFormat.getImageableX()),
                                       next_row);
                   Color current_color = g2.getColor();
                   g2.setColor(Color.lightGray);
                   int y = next_row + fontMetrics.getDescent();
                   g2.draw(new Line2D.Double(pageFormat.getImageableX(),
                                  y,
                                  (pageFormat.getImageableY() + pageFormat.getImageableWidth()),
                                  y));
                   g2.setColor(current_color);
                   next_row += fontMetrics.getHeight();
              next_row = printLine(g2, pageFormat, fontMetrics, -1, next_row, columnWidths);
              g2.setFont(defaultFont);
              fontMetrics = g2.getFontMetrics();
              // Start printing the detail
              ArrayList page = (ArrayList)pages.get(pageIndex);
              int start = ((Integer)page.get(0)).intValue();
              int end = ((Integer)page.get(1)).intValue();
              for (int i = start; i <= end; i++)
                   next_row = printLine(g2, pageFormat, fontMetrics, i, next_row, columnWidths);
              // Print the footer
              g2.setFont(footerFont);
              String pageFooter = "Page " + (pageIndex + 1) + " - " + lastPrintDate;
              g2.drawString(pageFooter,
                             (int)pageFormat.getWidth() / 2 - (fontMetrics.stringWidth(pageFooter) / 2),
                             (int)(pageHeight - fontDescent));
              return PAGE_EXISTS;
         * We can't guarantee that the same amount of rows will be displayed on each page,
         * the row heights are dynamic and may wrap onto 2 or more lines.
         * Thus we need to calculate the height of each row and then test how may rows
         * fit on a specific page. eg. Page 1 contains rows 1 to 10, Page 2 contains rows 11 to 15 etc.
         public void calcPages(Graphics g, PageFormat pageFormat) throws PrinterException
              Graphics2D     g2 = (Graphics2D) g;
              g2.setColor(Color.black);
              // The footer will be one line at the bottom of the page, cater for this.
              g2.setFont(footerFont);
              footerHeight = g2.getFontMetrics().getHeight() + g2.getFontMetrics().getDescent();
              g2.setFont(defaultFont);
              FontMetrics fontMetrics = g2.getFontMetrics();
              int fontHeight = fontMetrics.getHeight();
              int fontDescent = fontMetrics.getDescent();
              double pageHeight = pageFormat.getImageableHeight() - fontHeight;
              double pageWidth = pageFormat.getImageableWidth();
              double tableWidth = (double) tableView.getColumnModel().getTotalColumnWidth();
              // Shrink or expand the table to fit the page width
              double scale = (pageWidth - (cellBuffer * tableView.getColumnCount())) / tableWidth;
              // Calculate the width in pixels for each column
              double[] columnWidths = new double[tableView.getColumnCount()];
              for(int i = 0; i < tableView.getColumnCount(); i++)
                   columnWidths[i] = (double)Math.floor(tableView.getColumnModel().getColumn(i).getWidth() * scale);
              // Calculate the header height
              int maxHeight = 0;
              g2.setFont(headerFont);
              fontMetrics = g2.getFontMetrics();
              headerHeight = 0;
              if ((m_title != null) && (!m_title.equalsIgnoreCase("")))
                   headerHeight = fontMetrics.getHeight();
              for (int j = 0; j < tableView.getColumnCount(); j++)
                   String value = tableView.getColumnName(j).toString();
                   int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                   if (numLines > maxHeight)
                        maxHeight = numLines;
              headerHeight += g2.getFontMetrics().getHeight() * maxHeight;
              g2.setFont(defaultFont);
              fontMetrics = g2.getFontMetrics();
              int pageNum = 0;
              int bottom_of_page = (int)(pageFormat.getImageableHeight() + pageFormat.getImageableY()) - footerHeight;
              int prev_row = 0;
              int next_row = (int)pageFormat.getImageableY() + fontHeight + headerHeight;
              int i = 0;
              ArrayList page = new ArrayList();
              page.add(new Integer(0));
              for (i = 0; i < tableView.getRowCount(); i++)
                   maxHeight = 0;
                   for (int j = 0; j < tableView.getColumnCount(); j++)
                        String value = formatObject(tableView.getValueAt(i, j));
                        int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                        if (numLines > maxHeight)
                             maxHeight = numLines;
                   prev_row = next_row;
                   next_row += (fontHeight * maxHeight);
                   // If we've reached the bottom of the page then set the current page's end row
                   if (next_row > bottom_of_page)
                        page.add(new Integer(i - 1));
                        pages.add(page);
                        page = new ArrayList();
                        page.add(new Integer(i));
                        pageNum++;
                        next_row = (int)pageFormat.getImageableY()
                                       + fontHeight
                                       + ((int)pageFormat.getHeight() * pageNum)
                                       + headerHeight;
                        bottom_of_page = (int)(pageFormat.getImageableHeight()
                                            + pageFormat.getImageableY())
                                            + ((int)pageFormat.getHeight() * pageNum)
                                            - footerHeight;
                        //Include the current row on the next page, because there is no space on this page
                        i--;
              page.add(new Integer(i - 1));
              pages.add(page);
         * Print the headers or a row from the table to the graphics context
         * Return the position of the row following this one
         public int printLine(Graphics2D g2,
                                       PageFormat pageFormat,
                                       FontMetrics fontMetrics,
                                       int rowNum,
                                       int next_row,
                                       double[] columnWidths)
                   throws PrinterException
              int lead = 0;
              int maxHeight = 0;
              for (int j = 0; j < tableView.getColumnCount(); j++)
                   String value = null;
                   int align = LEFT_ALIGN;
                   if (rowNum > -1)
                        Object obj = tableView.getValueAt(rowNum, j);
                        if (obj instanceof Number)
                             align = RIGHT_ALIGN;
                        value = formatObject(obj);
                   else
                        //align = CENTER_ALIGN;
                        value = tableView.getColumnName(j);
                   int numLines = (int)Math.ceil(fontMetrics.stringWidth(value) / columnWidths[j]);
                   if (numLines > maxHeight)
                        maxHeight = numLines;
                   if (fontMetrics.stringWidth(value) < columnWidths[j])
                        // Single line
                        int offset = 0;
                        // Work out the offset from the start of the column to display alignment correctly
                        switch (align)
                             case RIGHT_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)); break;
                             case CENTER_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value)) / 2; break;
                             default: offset = 0; break;
                        g2.drawString(value,
                                       lead + (int)(pageFormat.getImageableX() + offset),
                                       next_row);
                   else
                        for(int a = 0; a < numLines; a++)
                             //Multi-Line
                             int x = 0;
                             int width = 0;
                             for(x = 0; x < value.length(); x++)
                                  width += fontMetrics.charWidth(value.charAt(x));
                                  if (width > columnWidths[j])
                                       break;
                             int offset = 0;
                             // Work out the offset from the start of the column to display alignment correctly
                             switch (align)
                                  case RIGHT_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value.substring(0, x))); break;
                                  case CENTER_ALIGN: offset = (int)(columnWidths[j] - fontMetrics.stringWidth(value.substring(0, x))) / 2; break;
                                  default: offset = 0; break;
                             g2.drawString(value.substring(0, x),
                                            lead + (int)(pageFormat.getImageableX() + offset),
                                            next_row + (fontMetrics.getHeight() * a));                    
                             value = value.substring(x);
                   lead += columnWidths[j] + cellBuffer;
              // Draw a solid line below the row
              Color current_color = g2.getColor();
              g2.setColor(Color.lightGray);
              int y = next_row + (fontMetrics.getHeight() * (maxHeight - 1)) + fontMetrics.getDescent();
              g2.draw(new Line2D.Double(pageFormat.getImageableX(),
                             y,
                             (pageFormat.getImageableY() + pageFormat.getImageableWidth()),
                             y));
              g2.setColor(current_color);
              // Return the position of the row following this one
              return next_row + (fontMetrics.getHeight() * maxHeight);
         public String formatObject(Object obj)
              String value = (obj == null) ? "" : obj.toString();
              return value;

  • Unable to specify printer for print jobs in Java7 for OSX

    Hi, I'm developing a simple software that would monitor a folder for new documents and print them automatically. Monitoring the folder was the easy part with WatchService in Java7, but I'm running into problems with printing. Namely, I'm using java.awt.print.PrinterJob to print the document, but the print job is always sent to the default printer, instead of the printer that was specified.
    PrinterJob pPrinterJob = PrinterJob.getPrinterJob();
    PrintService[] psArr = PrinterJob.lookupPrintServices();
    for (PrintService ps : psArr) {
    if (ps.getName().equalsIgnoreCase(specifiedPrinterName)) {
    pPrinterJob.setPrintService(ps);
    break;
    PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
    //specify print attributes....
    pPrinterJob.print(pras);
    The code looks simple enough, and calling getPrinterService() returns the intended printer after specifying it using setPrinterService(). However, regardless of the printer specified, the print job is still sent to the default printer. Tried on both Java 7 Update 4 and Update 6 for OSX with the same result.
    Update: Got my hands on a Win XP machine and tried out the same piece of code using Java 7 Update 6 for Windows. Guess what, the print job was sent to the specified printer! I'm pretty sure this is an OSX specific issue now. Has anyone come across this issue previously?

    Hi,
    I have the exact same problem on OS X 10.8.2 with Java 1.7.0 Update 21.
    When I call PrintServiceLookup.lookupPrintServices(null, null) I get three distinct printers, but no matter which of the three I specify, the print job is sent to the default printer.
    The code works as expected when tested on Windows and Linux machines.
    Any help is appreciated!

  • CHOOSE PRINTER

    Hi guys, I am creating an application with FORMS RUNTIME. Now, in one of my forms I need to create a button that pops up some kind of LOV or POPLIST or whatever it is, with the possible PRINTERS for the machine. Is there some sort of built in, ora an ADD ON..
    It would really be helpfull,
    Thanks.

    Hi,
    First off, please always indicate which version of Forms you're using, whether your forms are client/server or web-deployed, and the client OS. Someone else may have better suggestions, but here are a few ideas:
    If you are working with client/server forms on Windows, I would look into the possibility of calling EnumPrinters via ORA_FFI. If you are unfamiliar with the C language and/or the Windows API, this approach will make for a rough introduction.
    As an easier approach I would consider using a JavaBean. I quickly wrote the following bean that exposes one method -- getPrinterList( ). This method returns a semicolon-delimited list of all installed printers:
        import java.awt.print.*;
        import javax.print.PrintService;
        import oracle.forms.ui.VBean;
        public class PrinterEnumerator extends VBean {
          public String getPrinterList() {
            StringBuffer sb = new StringBuffer();
            PrintService[] ps = PrinterJob.lookupPrintServices();
            for (int i=0; i<ps.length; i++) {
              sb.append(ps[ i ].getName());
              sb.append(";");
            return sb.toString();
        }I'm not sure whether JavaBeans are an option for client/server forms, but I'm fairly certain that they are. The only catch here is that web forms provide a means for automatically copying beans over to the client PC -- client/server will most likely require you to make that happen.
    As for loading a poplist programmatically, see the Forms documentation.
    Sorry if these suggestions are a bit sketchy -- they should at least point you in the right direction.
    Hope this helps,
    Eric Adamson
    Lansing, Michigan

  • Using device fonts for printing

    Hello,
    I was wondering how to use device fonts in Java. These are the fonts that are in the printer and not in the operating system.
    I'm writing some point of sale software that needs to use the Star TSP100 printer on Windows 7 64.
    I need to use the device font "control" in order to instruct the printer to open the cash drawer.
    I would also like to use the device font "3of9" for barcodes. I know there are alternatives to using this, but directly from the printer would be easier than trying to purchase and deploy a barcode font.
    I know that star micronics has a JPOS implementation, but not for windows 7 64. And the JPOS with the StarMicronics bin is cumbersome and unstable for the end user even in Windows XP 32 bit.
    If I specify the font "control" java replaces it with the default font. i.e. Font deviceFont = new Font ("control", Font.PLAIN, 8.5); is just the default font and not "control"

    I did find a solution to my problem, but I cannot use device fonts. You may also find this useful to address your issue. I opened the a print service and sent ASCII to it instead of creating and printing a graphic object. You'll need the [Command Emulator STAR Line Mode Command Specifications|http://www.star-micronics.co.jp/eng/service/usermanual/comemu_starline_pm.pdf] to know what the commands are for the TSP100 and TSP700. I've included a cheat sheet to find the HEX value of the ASCII command. Note that if you need to send several characters you'll need to use the space with it.
    e.g. The command to select font is ESC RS F you'll need to send: 1B201E2046
    My Chizzle:
    package recptpkg;
    import javax.print.PrintService;
    import java.awt.print.PrinterJob;
    import javax.print.DocPrintJob;
    import javax.print.Doc;
    import javax.print.DocFlavor;
    import javax.print.SimpleDoc;
    public class openCashDrawer {
        boolean showStatus;  // false if error
        public openCashDrawer() {
            showStatus = false;
            PrinterJob printerJob;
            PrintService psTSP100 = null;
            PrintService[] ps = PrinterJob.lookupPrintServices();
            for (int i = 0; i < ps.length; i++) {
                if (ps.getName().indexOf("Star TSP100 Cutter (TSP143)") >= 0) {
    psTSP100 = ps[i];
    if (psTSP100 == null) {
    System.out.println("Aw SNAP! I like, can't find a printer with "
    + "Star TSP100 Cutter (TSP143) in the name");
    showStatus = false;
    try {
    DocPrintJob job = psTSP100.createPrintJob();
    String openDrawer1Command = ((char) 0x07) + "";
    byte by[] = openDrawer1Command.getBytes();
    DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
    Doc doc = new SimpleDoc(by, flavor, null);
    job.print(doc, null);
    } catch (Exception e) {
    System.out.println("Whoa bro. The printer is balls. Check it:");
    e.printStackTrace();
    try {
    DocPrintJob job = psTSP100.createPrintJob();
    String openDrawer2Command = ((char) 0x1A) + "";
    byte by[] = openDrawer2Command.getBytes();
    DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
    Doc doc = new SimpleDoc(by, flavor, null);
    job.print(doc, null);
    showStatus = true;
    } catch (Exception e) {
    System.out.println("Whoa bro. The printer is balls. Check it:");
    e.printStackTrace();
    showStatus = false;
    public boolean getStatus() {
    return showStatus;
    //ASCII Cheat Sheet:
    /* 00 NUL | 01 SOH | 02 STX | 03 ETX | 04 EOT | 05 ENQ | 06 ACK | 07 BEL
    08 BS | 09 HT | 0A LF | 0B VT | 0C FF | 0D CR | 0E SO | 0F SI
    10 DLE | 11 DC1 | 12 DC2 | 13 DC3 | 14 DC4 | 15 NAK | 16 SYN | 17 ETB
    18 CAN | 19 EM | 1A SUB | 1B ESC | 1C FS | 1D GS | 1E RS | 1F US
    20 SP | 21 ! | 22 " | 23 # | 24 $ | 25 % | 26 & | 27 '
    28 ( | 29 ) | 2A * | 2B + | 2C , | 2D - | 2E . | 2F /
    30 0 | 31 1 | 32 2 | 33 3 | 34 4 | 35 5 | 36 6 | 37 7
    38 8 | 39 9 | 3A : | 3B ; | 3C < | 3D = | 3E > | 3F ?
    40 @ | 41 A | 42 B | 43 C | 44 D | 45 E | 46 F | 47 G
    48 H | 49 I | 4A J | 4B K | 4C L | 4D M | 4E N | 4F O
    50 P | 51 Q | 52 R | 53 S | 54 T | 55 U | 56 V | 57 W
    58 X | 59 Y | 5A Z | 5B [ | 5C   \ | 5D   ] | 5E ^ | 5F _
    60 ` | 61 a | 62 b | 63 c | 64 d | 65 e | 66 f | 67 g
    68 h | 69 i | 6A j | 6B k | 6C l | 6D m | 6E n | 6F o
    70 p | 71 q | 72 r | 73 s | 74 t | 75 u | 76 v | 77 w
    78 x | 79 y | 7A z | 7B { | 7C | | 7D } | 7E ~ | 7F DEL */
    {code}
    Edited by: StoneBrooks on Sep 10, 2010 11:24 AM

  • Feature Request: Setting App page title to something other than "Eloqua 10"

    Hello everyone,
    Long-time lurker, first-time poster. As someone who has been using Eloqua for over 3 years, when working in the application, I will usually end up with upwards of half-a-dozen tabs open in Firefox, all of which say "Eloqua 10". Because of this, I'll usually try to strategically organize my tabs, but often times I end up having to click through multiple tabs to find the one I'm looking for, which can sometimes lead to Firefox freezing. I'm sure I'm not alone in this.
    So to alleviate this, I'd like to make the following feature request: Can we have the tabs/windows named by Asset Type & Asset Name? Perhaps in the following Format:
    [Asset Type]: [Asset Name] - Eloqua 10
    Note how I have "Eloqua 10" at the end of the string. An example of a title would be: "Campaigns: Nurture_Campaign_1 - Eloqua 10"
    Could this please be implemented?
    Thank you,
    Sean

    Here is a snippet of code that I wrote and use without any problem:
       public void ppPrint() {
          if (printJob==null) initPrintJob();
          try {
             if (!printJob.printDialog(aset)) return;
          } catch (Throwable e) {
       public void initPrintJob() {
          aset=new HashPrintRequestAttributeSet();
          aset.add(new JobName("AOKabc",null));
          aset.add(new MediaPrintableArea(.75f,.25f,7.5f,10.5f,MediaPrintableArea.INCH));
          printJob=PrinterJob.getPrinterJob();      
    /* locate a print service that can handle the request */
          PrintService[] services=PrinterJob.lookupPrintServices();
          if (services.length==0) System.out.println("Warning: No printer detected!");
          else {
             try {
                printJob.setPrintService(services[0]);
             } catch (Throwable pe) { }
          pageFormat=printJob.defaultPage();
          Paper paper=new Paper();
          paper.setImageableArea(54,18,540,756);
          pageFormat.setPaper(paper);
          printJob.setPrintable(Preview.this);
       };o)
    V.V.

  • PrintServiceLookup.lookup in Tomcat

    Hi Forum,
    How could I get javax.print.PrintServiceLookup.lookupPrintServices(null,null) to return the current available services while the program that uses lookupPrintServices is running? In a tomcat servlet, I use the lookupPrintServices(..) to get a list of the printer services available. The class works well and returns the
    list but if I install a new printer, the servlet does not list the newly installed service until I restart Tomcat.
    Is there a way to unload and reload the PrintServiceLookup class and then call PrintServiceLookup.lookupPrintServices?
    It appears that the lookupPrintServices(..) returns the list of services that was available when the instance of the virtual machine was started. Hence, while the instance is running, it allways returns the same list of
    services. If I run a program that lists the services and then exits, the program lists the newly added printer on re-run. But if the program never exits (it runs in a loop, re-listing the services every so often), and I add
    a new printer while the program is running, the newly added printer is not listed until I terminate the pogram and re-start it.
    Thanks in advance for your response

    Thank for your response,
    It appears that there is a bug in the JDK. A bug reported against the SUN JDK for this problem and it seeems that the bug has not been resolved yet.
    A ling to the bug: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4744405
    A brief description of the reported bug:
    Bug ID: 4744405
    Votes 17
    Synopsis RFE: lookupPrintServices() to refresh the printers list dynamically
    Category java:classes_2d
    Reported Against 1.4 , 1.4.1
    Release Fixed
    State In progress, request for enhancement
    Related Bugs 5028849 , 5033703
    Submit Date 10-SEP-2002
    Description *This also happened on Windows platform.
    java version "1.4.1-rc"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.1-rc-b19)
    Java HotSpot(TM) Client VM (build 1.4.1-rc-b19, mixed mode)
    When invoke method lookupPrintServices() on class PrinterJob or PrintServiceLookup, the printers list can not refreshed when adding or deleting printers dynamically.
    Steps to follow to reproduce the problem:
    1. Compile and run the included test case
    2. The print dialog shows up and avaible printers information is printed out on screen. Click "cancel" to dismiss the dialog. The test case is pending.
    3. Use Printer Selector Tool to add a new printer into selected printers list and save changes.
    4. Back to the terminal that run the test case an click "enter" button to continue. Then a new thread will be created to invoke the lookupPrintServices() and pop up the print dialog again.
    5. The screen output shows that invoking lookupPrintServices() doesn't reflect the newly added printer information, neither does the print dialog.
    //-------- source code begin-----------//
    import java.awt.print.*;
    import javax.print.*;
    public class MTPrinterTest extends Thread {
    public static void main(String[] args) {
    MTPrinterTest t1 = new MTPrinterTest();
    t1.start();
    try {
    System.in.read();
    } catch (Exception e){}
    MTPrinterTest t2 = new MTPrinterTest();
    t2.start();
    public void run() {
    PrinterJob printerJob;
    PrintService[] printServices;
    printerJob = PrinterJob.getPrinterJob();
    printServices = printerJob.lookupPrintServices();
    System.out.println("Number of servies found: " + printServices.length);
    for (int i =0; i< printServices.length; i++)
    System.out.println("--> Available Printer " + i + ": " + printServices);
    printerJob.printDialog();
    //-------- source code end ----------//
    Work Around Exit the current running application and run it again, then the printers list get refreshed. Seems the running JVM can not get updated printer information

Maybe you are looking for

  • Jabber For Windows - Available Status on Hibernation

    We're running Jabber for Windows 9.1.1 ansd see an issue which I think is casued by hiberantion. A laptop user will be at their pc and and Available, then on leaving their desk, they would typically just close their pc lid, hibernating the pc,  and l

  • Working Sets not working

    Has anyone got Working Sets to work with Flash Builder 4.5 for PHP as described here: http://help.adobe.com/en_US/flashbuilder/using/WSc5cd04c102ae3e97bf51ac512e1410bae5-7ff6.h tml I created an entirely new workspace to see if that might be the issue

  • Please Help Me!!! I have problem while installing 11g RAC on Windows!!!

    Guys, I have to configure a test environment on my pc. I need a 2-node RAC system which will run on Windows. Problem is this: I'm creating two networks on my nodes, public and private but when i come to grid installation, Oracle can not identify my n

  • Unable to email photos

    I wanted to email a photo to BBC South Today. It keeps getting returned, Error 552 -  exceeds message size. The first photo I sent was 9.32MB . I thought this would be ok as up to 25 MB is allowed?  I then resized it on photoshop to  5.52 MB, but thi

  • Help!!! Stateful session bean clustering

              I posted this message on interest.clustering.in-memory-replication. But there is           no answer at all. Could anyone give me           some hints? Thanks a lot. I am a student and this work is part of my course project.           It is