To print a offscreen JFrame

Hi!
I have a offscreen JFrame with different panels. I want to print this JFrame, but it seems that it is only possible when the JFrame is visible.
I have searched through the Forums and found a lot answers about how to manage offscreen images, but in this case its a JFrame what I need to be printed.
Thanks in advance!
F�lix

Thanks KPSeal!
I tried with your code, but I get the same problem, only if the frame inside the JFramePrintable is visible, the content of the original frame is painted. If the frame is not visible, nothing (that's to say, a white page) is printed.
Maybe the problem is the way I call the frame to be printed.
Here send you a snippet with my code:
  private boolean applyChanges(){
      //Print the offscreen frame
        JFrame mjf=new JFrame();
        MyClassWithInfo info=new MyClassWithInfo();//That's what I want to be displayed (a JPanel with information)
        mjf.setBounds(0,0,190,140);
        mjf.getContentPane().setLayout(new BorderLayout());
        mjf.getContentPane().add(info,BorderLayout.CENTER);
        JFramePrintable jfp=new JFramePrintable(mjf);
//        jfp.frame.setVisible(true); //only when this line is active, I get something....
        PrinterJob pj = PrinterJob.getPrinterJob();
        PageFormat pageFormat = pj.defaultPage();
        try {
            pageFormat.setOrientation(java.awt.print.PageFormat.LANDSCAPE);
            //A new paper object with our settings is created
            Paper paper=new Paper();
            paper.setImageableArea(10,10,545,820);
            paper.setSize(595,841);
            pageFormat.setPaper(paper);
        } catch (Exception ex) { }
        pj.setPrintable(jfp,pageFormat);
        if (pj.printDialog()) {
            try {
                pj.print();
            catch (Exception p) {
        else{
          return false;
    return true;
  }

Similar Messages

  • How to print the whole JFrame

    Hi,
    I got this code somewhere from the net.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.print.*;
    /** A simple utility class that lets you very simply print
    *  an arbitrary component. Just pass the component to the
    *  PrintUtilities.printComponent. The component you want to
    *  print doesn't need a print method and doesn't have to
    *  implement any interface or do anything special at all.
    *  <P>
    *  If you are going to be printing many times, it is marginally more
    *  efficient to first do the following:
    *  <PRE>
    *    PrintUtilities printHelper = new PrintUtilities(theComponent);
    *  </PRE>
    *  then later do printHelper.print(). But this is a very tiny
    *  difference, so in most cases just do the simpler
    *  PrintUtilities.printComponent(componentToBePrinted).
    *  7/99 Marty Hall, http://www.apl.jhu.edu/~hall/java/
    *  May be freely used or adapted.
    public class PrintUtilities implements Printable {
      private JFrame componentToBePrinted;
      public static void printComponent(JFrame c) {
        new PrintUtilities(c).print();
      public PrintUtilities(JFrame componentToBePrinted) {
        this.componentToBePrinted = componentToBePrinted;
      public void print() {
        PrinterJob printJob = PrinterJob.getPrinterJob();
        printJob.setPrintable(this);
        if (printJob.printDialog())
          try {
            printJob.print();
          } catch(PrinterException pe) {
            System.out.println("Error printing: " + pe);
      public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
        if (pageIndex > 0) {
          return(NO_SUCH_PAGE);
        } else {
          Graphics2D g2d = (Graphics2D)g;
          g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
          disableDoubleBuffering(componentToBePrinted);
          componentToBePrinted.paint(g2d);
          enableDoubleBuffering(componentToBePrinted);
          return(PAGE_EXISTS);
      /** The speed and quality of printing suffers dramatically if
       *  any of the containers have double buffering turned on.
       *  So this turns if off globally.
       *  @see enableDoubleBuffering
      public static void disableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(false);
      /** Re-enables double buffering globally. */
      public static void enableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(true);
    }From my main class (where the JFrame resides), the print() method is invoked to print the JFrame. However, when it is printed, it only prints the top left part of the JFrame, not the whole JFrame. Can anyone help please? Thank you very much.

    public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
        if (pageIndex > 0) {
          return(NO_SUCH_PAGE);
        else {
          Graphics2D g2d = (Graphics2D)g;     
          g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
           double xScale = 0.63;
           double yScale = 0.56;
          g2d.scale(xScale, yScale);
          disableDoubleBuffering(componentToBePrinted);     
          componentToBePrinted.paint(g2d);
          enableDoubleBuffering(componentToBePrinted);
          return(PAGE_EXISTS);
      }Hi all,
    Alright I managed to scale it to print the whole JFrame. But another problem surfaces. When I select draft quality printing, it doesn't print the whole JFrame. Other printing qualities (standard, high) do print the whole JFrame. I am really puzzled. Anyone has any clue?
    And I have an unrelated question to this topic. How do I set a JTextField so that when I click on it the first time, it highlights its content? Have to work around with the mouselistener?
    Thank you.

  • Print option:-  to print the entire JFrame and its components

    I have created a screen using JFrame.
    The screen contains components such as a graph, combobox, tabbedpane and JTable.
    Now we have given 2 options to the end user, either to print the entire screen(JFrame) or
    the contents available in the table.
    My query is , how can i print the entire screen(all the components must be printed),
    is there any api available for this purpose.
    If possible provide me some sample codes.

    <h3>{color:#ff0000}Cross posted{color}</h3>
    [http://forum.java.sun.com/thread.jspa?threadID=5286030]
    Cross posting is rude.
    db

  • Print out a JFrame !

    Hi all....
    i have many panels and texts and Tables ... All are inside a JFrame (or a JTabbedPane)
    My Question is sooooo simple :
    How to Print this JFrame (or JTabbedPane) ?!
    i searched the web and found so many codes but they r all so complicated...
    Please any body help me with a VERY SIMPLE code doing that ?!!
    (Note : the JFrame has the same dimension as an A4 Paper)
    many many Thanks...

    ellias2007 wrote:
    Hi all....
    i have many panels and texts and Tables ... All are inside a JFrame (or a JTabbedPane)
    My Question is sooooo simple :What makes you think that is sooooo simple?
    How to Print this JFrame (or JTabbedPane) ?!
    i searched the web and found so many codes but they r all so complicated...If you have code that is too complicated, and you've searched for simpler, then what makes you think you're going to understand what we give you here?
    If you have an attempt, with your own code, please post it and we'll be glad to help you understand how to get it running, but without that, then how are we to know what is sooooo simple and what is complicated to you?

  • Can't print JFrame

    Hi,
    i am trying to print out a JFrame that contains other Swing and AWT components, such as JTables and menus etc.
    The problem is that the options that i select from the pageformat dialog, so not get set when the printing is taking place. As a result my jframe gets cut up into 4 differnet bits and each comes out on a seperate page. I cannot specify number of copies or size of paper either. Also once the ok button is pressed on the print dialogue, then the print dialogue comes back again and i have to press Ok, or Cancel to get rid of it. My code is below, please can someone suggest anything:
    ]public int print(Graphics g, PageFormat pf, int pi) throws PrinterException
              if (pi >= 1)
                   return Printable.NO_SUCH_PAGE;
              Graphics2D g2 = (Graphics2D) g;
              g2.translate(pf.getImageableX(), pf.getImageableY());
              g2.setColor(Color.black);
              paint(g2);
              return Printable.PAGE_EXISTS;
    PrinterJob pjob = PrinterJob.getPrinterJob();
    PageFormat pf = pjob.defaultPage();
    pjob.setPrintable(TransponderGraph.this, pf);
    try
    pjob.print();
    catch (PrinterException e) { }

    Just comment this line frame.setAlwaysOnTop(x);

  • Problem with printing JFrame with several other components on it

    Hi,
    i am trying to print out a JFrame that contains other Swing and AWT components, such as JTables and menus etc.
    The problem is that the options that i select from the pageformat dialog, do not get set when the printing is taking place. As a result my jframe gets cut up into 4 differnet bits and each comes out on a seperate page. I cannot specify number of copies or size of paper either. Also once the ok button is pressed on the print dialogue, then the print dialogue comes back again and i have to press Ok, or Cancel to get rid of it. My code is below, please can someone suggest anything:
    ]public int print(Graphics g, PageFormat pf, int pi) throws PrinterException
    if (pi >= 1)
    return Printable.NO_SUCH_PAGE;
    Graphics2D g2 = (Graphics2D) g;
    g2.translate(pf.getImageableX(), pf.getImageableY());
    g2.setColor(Color.black);
    paint(g2);
    return Printable.PAGE_EXISTS;
    PrinterJob pjob = PrinterJob.getPrinterJob();
    PageFormat pf = pjob.defaultPage();
    pjob.setPrintable(TransponderGraph.this, pf);
    try
    pjob.print();
    catch (PrinterException e) { }

    Ok, try this.
    Change this:
    <link href="
    http://www.jonbarron.org/css/style.css"
    rel="stylesheet" type="text/css" />
    to this:
    <link href="
    http://www.jonbarron.org/css/style.css"
    rel="stylesheet" type="text/css" media="screen" />
    Somewhere in that stylesheet lies your problem.

  • Printing a JFrame -- it doesn't fit in one page

    Hi, All:
    I like to print out a JFrame to a page. But the JFrame is too big to fit o a page. Does anyone know how to shrink it down and it would fit in a page? The PageFormat I am using is landscape.
    Any help is appreciated!
    Tiny

    Hi TinyBone,
    I am not responding to your current question. I am actually experiencing a problem you had some time ago. You didn't get any responses....but I'm wondering if you ever figured it out. I am getting a -2 when using executeBatch just like you did and can't figure-out why or how to fix it. Would you mind emailing me at [email protected] and tell me whether you ever solved this or not? If so, how?
    Thanks,
    hercules1000
    Hi, your help is greatly appreciated.
    My problem is:
    executeBatch() is returning a array of -2, according to the api,
    commands executed successfully, but the rows affected are
    unknow. Is there any way to fix this so executeBatch() will
    return the correct number?
    Thanks,
    TinyBone

  • Print JFrame without title bar and border

    I am trying to print out a JFrame which contains two JPanels. The following code is part of my implementation of Printable which prints the entire JFrame including the title bar and border. I've considered implementing Printable in the JPanel classes but then I don't know how I would get everything on one page as a single image. Is there some way to just print the contentPane of the JFrame?
         public int print(Graphics g, PageFormat pf, int pi)
              throws PrinterException {
              if (pi >= 1) {
                   return Printable.NO_SUCH_PAGE;
              Graphics2D g2 = (Graphics2D) g;
              double scaleX = pf.getImageableWidth()/getWidth();
              double scaleY = pf.getImageableHeight()/getHeight();
              double scale = 1;
              g2.translate((int) pf.getImageableX(), (int) pf.getImageableY());
              if (scaleX < 1 || scaleY < 1) {
                   scale = scaleX < scaleY ? scaleX : scaleY;
                   g2.scale(scale,scale);
              printAll(g2);
              return Printable.PAGE_EXISTS;
         }                    

    Thanks.
    I can get the Jframe without the title bar and I can get it to drag on the desktop with your suggestions. I still need it to have rounded edges.

  • Is it possible to print JTable and custom JPanel on the same page?

    Hello everybody!
    I have a custom panel extending JPanel and implementing Printable.
    I am using paint() method to draw some graphics on it's content pane. I would like to print it, but first I would like to add a JTable at the bottom of my panel. Printing just the panel goes well. No problems with that.
    I was also able to add a JTable to the bottom of JFrame, which contains my panel.
    But how can I print those two components on one page?

    Hi, thanks for your answer, but I thought about that earlier and that doesn't work as well... or mybe I'm doing something wrong. Here is the sample code:
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.print.PageFormat;
    import java.awt.print.Printable;
    import java.awt.print.PrinterException;
    import java.awt.print.PrinterJob;
    import javax.print.attribute.HashPrintRequestAttributeSet;
    import javax.swing.JFrame;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTable;
    public class ReportFrame extends JFrame implements Printable {
         private static final long serialVersionUID = -8291124097290245799L;
         private MyPanel rp;
         private JTable reportTable;
         private HashPrintRequestAttributeSet attributes;
         public ReportFrame() {
              rp = new MyPanel();
              String[] columnNames = { "Column1", "Column2", "Column3" };
              String[][] values = { { "Value1", "Value2", "Value3" }, { "Value4", "Value5", "Value6" }, { "Value7", "Value8", "Value9" } };
              reportTable = new JTable(values, columnNames);
              add(rp, BorderLayout.CENTER);
              add(reportTable, BorderLayout.SOUTH);
              setTitle("Printing example");
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setPreferredSize(new Dimension(700, 700));
              pack();
              setVisible(true);
         @Override
         public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
              if (pageIndex >= 1)
                   return Printable.NO_SUCH_PAGE;
              Graphics2D g2D = (Graphics2D) graphics;
              g2D.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
              return Printable.PAGE_EXISTS;
         public static void main(String[] args) {
              new ReportFrame().printer();
         class MyPanel extends JPanel implements Printable {
              private static final long serialVersionUID = -2214177603101440610L;
              @Override
              public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
                   if (pageIndex >= 1)
                        return Printable.NO_SUCH_PAGE;
                   Graphics2D g2D = (Graphics2D) graphics;
                   g2D.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
                   return Printable.PAGE_EXISTS;
              @Override
              public void paint(Graphics g) {
                   super.paintComponent(g);
                   Graphics2D g2D = (Graphics2D) g;
                   int x = 0, y = 0, width = 70, height = 70;
                   for (int i = 0; i < 50; i++) {
                        g2D.drawOval(x + i * 10, y + i * 10, width, height);
         public void printer() {
              try {
                   attributes = new HashPrintRequestAttributeSet();
                   PrinterJob job = PrinterJob.getPrinterJob();
                   job.setPrintable(this);
                   if (job.printDialog(attributes))
                        job.print(attributes);
              } catch (PrinterException e) {
                   JOptionPane.showMessageDialog(this, e);
    }UPDATE:
    I've managed to get this to work, by calling 2 methods inside the outer frame's print method (lines 78 and 79)
    Those two methods are:
    rp.paint(g2D);
    reportTable.paint(g2D);but still it is not the way I would like it to be.
    First of all both the ReportPanel and ReportTable graphics are printed with the upper-left corner located in the upper-left corner of the JFrame and the first one is covering the second.
    Secondly, I would like to rather implemet the robust JTable's print method somehow, because it has some neat features like multipage printing, headers & footers. But I have no idea how to add my own graphics to the JTables print method, so they will appear above the JTable. Maybe someone knows the answer?
    Thanks a lot
    UPDATE2:
    I was googling nearly all day in search of an answer, but with no success. I don't think it's possible to print JTable using it's print() method together with other components, so I will have to think of something else i guess...
    Edited by: Adalbert23 on Nov 22, 2007 2:49 PM

  • Help needed:Printing HTML file using javax.print

    Hi
    I am using the following code which i got form the forum for rpinting an HTML file.
    The folllowing code is working fine, but the problem is the content of HTML file is not getting printed. I am geeting a blank page with no content. What is the change that is required in the code? ALso is there any simpler way to implement this. Help needed ASAP.
    public boolean printHTMLFile(String filename) {
              try {
                   JEditorPane editorPane = new JEditorPane();
                   editorPane.setEditorKit(new HTMLEditorKit());
                   //editorPane.setContentType("text/html");
                   editorPane.setSize(500,500);
                   String text = getFileContents(filename);
                   if (text != null) {
                        editorPane.setText(text);                    
                   } else {
                        return false;
                   printEditorPane(editorPane);
                   return true;
              } catch (Exception tce) {
                   tce.printStackTrace();
              return false;
         public String getFileContents(String filename) {
              try {
                   File file = new File(filename);
                   BufferedReader br = new BufferedReader(new FileReader(file));
                   String line;
                   StringBuffer sb = new StringBuffer();
                   while ((line = br.readLine()) != null) {
                        sb.append(line);
                   br.close();
                   return sb.toString();
              } catch (Exception tce) {
                   tce.printStackTrace();
              return null;
         public void printEditorPane(JEditorPane editorPane) {
                   try {
                        HTMLPrinter htmlPrinter = new HTMLPrinter();
                        htmlPrinter.printJEditorPane(editorPane, htmlPrinter.showPrintDialog());
                   } catch (Exception tce) {
                        tce.printStackTrace();
         * Sets up to easily print HTML documents. It is not necessary to call any of the setter
         * methods as they all have default values, they are provided should you wish to change
         * any of the default values.
         public class HTMLPrinter {
         public int DEFAULT_DPI = 72;
         public float DEFAULT_PAGE_WIDTH_INCH = 8.5f;
         public float DEFAULT_PAGE_HEIGHT_INCH = 11f;
         int x = 100;
         int y = 80;
         GraphicsConfiguration gc;
         PrintService[] services;
         PrintService defaultService;
         DocFlavor flavor;
         PrintRequestAttributeSet attributes;
         Vector pjlListeners = new Vector();
         Vector pjalListeners = new Vector();
         Vector psalListeners = new Vector();
         public HTMLPrinter() {
              gc = null;
              attributes = new HashPrintRequestAttributeSet();
              flavor = null;
              defaultService = PrintServiceLookup.lookupDefaultPrintService();
              services = PrintServiceLookup.lookupPrintServices(flavor, attributes);
              // do something with the supported docflavors
              DocFlavor[] df = defaultService.getSupportedDocFlavors();
              for (int i = 0; i < df.length; i++)
              System.out.println(df.getMimeType() + " " + df[i].getRepresentationClassName());
              // if there is a default service, but no other services
              if (defaultService != null && (services == null || services.length == 0)) {
              services = new PrintService[1];
              services[0] = defaultService;
         * Set the GraphicsConfiguration to display the print dialog on.
         * @param gc a GraphicsConfiguration object
         public void setGraphicsConfiguration(GraphicsConfiguration gc) {
              this.gc = gc;
         public void setServices(PrintService[] services) {
              this.services = services;
         public void setDefaultService(PrintService service) {
              this.defaultService = service;
         public void setDocFlavor(DocFlavor flavor) {
              this.flavor = flavor;
         public void setPrintRequestAttributes(PrintRequestAttributeSet attributes) {
              this.attributes = attributes;
         public void setPrintDialogLocation(int x, int y) {
              this.x = x;
              this.y = y;
         public void addPrintJobListener(PrintJobListener pjl) {
              pjlListeners.addElement(pjl);
         public void removePrintJobListener(PrintJobListener pjl) {
              pjlListeners.removeElement(pjl);
         public void addPrintServiceAttributeListener(PrintServiceAttributeListener psal) {
              psalListeners.addElement(psal);
         public void removePrintServiceAttributeListener(PrintServiceAttributeListener psal) {
              psalListeners.removeElement(psal);
         public boolean printJEditorPane(JEditorPane jep, PrintService ps) {
                   if (ps == null || jep == null) {
                        System.out.println("printJEditorPane: jep or ps is NULL, aborting...");
                        return false;
                   // get the root view of the preview pane
                   View rv = jep.getUI().getRootView(jep);
                   // get the size of the view (hopefully the total size of the page to be printed
                   int x = (int) rv.getPreferredSpan(View.X_AXIS);
                   int y = (int) rv.getPreferredSpan(View.Y_AXIS);
                   // find out if the print has been set to colour mode
                   DocPrintJob dpj = ps.createPrintJob();
                   PrintJobAttributeSet pjas = dpj.getAttributes();
                   // get the DPI and printable area of the page. use default values if not available
                   // use this to get the maximum number of pixels on the vertical axis
                   PrinterResolution pr = (PrinterResolution) pjas.get(PrinterResolution.class);
                   int dpi;
                   float pageX, pageY;
                   if (pr != null)
                        dpi = pr.getFeedResolution(PrinterResolution.DPI);
                   else
                        dpi = DEFAULT_DPI;
                   MediaPrintableArea mpa = (MediaPrintableArea) pjas.get(MediaPrintableArea.class);
                   if (mpa != null) {
                        pageX = mpa.getX(MediaPrintableArea.INCH);
                        pageY = mpa.getX(MediaPrintableArea.INCH);
                   } else {
                        pageX = DEFAULT_PAGE_WIDTH_INCH;
                        pageY = DEFAULT_PAGE_HEIGHT_INCH;
                   int pixelsPerPageY = (int) (dpi * pageY);
                   int pixelsPerPageX = (int) (dpi * pageX);
                   int minY = Math.max(pixelsPerPageY, y);
                   // make colour true if the user has selected colour, and the PrintService can support colour
                   boolean colour = pjas.containsValue(Chromaticity.COLOR);
                   colour = colour & (ps.getAttribute(ColorSupported.class) == ColorSupported.SUPPORTED);
                   // create a BufferedImage to draw on
                   int imgMode;
                   if (colour)
                        imgMode = BufferedImage.TYPE_3BYTE_BGR;
                   else
                        imgMode = BufferedImage.TYPE_BYTE_GRAY;
                   BufferedImage img = new BufferedImage(pixelsPerPageX, minY, imgMode);
                   Graphics myGraphics = img.getGraphics();
                   myGraphics.setClip(0, 0, pixelsPerPageX, minY);
                   myGraphics.setColor(Color.WHITE);
                   myGraphics.fillRect(0, 0, pixelsPerPageX, minY);
                        java.awt.Rectangle rectangle=new java.awt.Rectangle(0,0,pixelsPerPageX, minY);
                   // call rootView.paint( myGraphics, rect ) to paint the whole image on myGraphics
                   rv.paint(myGraphics, rectangle);
                   try {
                        // write the image as a JPEG to the ByteArray so it can be printed
                        Iterator writers = ImageIO.getImageWritersByFormatName("jpeg");
                        ImageWriter writer = (ImageWriter) writers.next();
                                       // mod: Added the iwparam to create the highest quality image possible
                        ImageWriteParam iwparam = writer.getDefaultWriteParam();
                        iwparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT) ;
                        iwparam.setCompressionQuality(1.0f); // highest quality
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        ImageOutputStream ios = ImageIO.createImageOutputStream(out);
                        writer.setOutput(ios);
                        // get the number of pages we need to print this image
                        int imageHeight = img.getHeight();
                        int numberOfPages = (int) Math.ceil(minY / (double) pixelsPerPageY);
                        // print each page
                        for (int i = 0; i < numberOfPages; i++) {
                             int startY = i * pixelsPerPageY;
                             // get a subimage which is exactly the size of one page
                             BufferedImage subImg = img.getSubimage(0, startY, pixelsPerPageX, Math.min(y - startY, pixelsPerPageY));
                                                 // mod: different .write() method to use the iwparam parameter with highest quality compression
                             writer.write(null, new IIOImage(subImg, null, null), iwparam);
                             SimpleDoc sd = new SimpleDoc(out.toByteArray(), DocFlavor.BYTE_ARRAY.JPEG, null);
                             printDocument(sd, ps);
                             // reset the ByteArray so we can start the next page
                             out.reset();
                   } catch (PrintException e) {
                        System.out.println("Error printing document.");
                        e.printStackTrace();
                        return false;
                   } catch (IOException e) {
                        System.out.println("Error creating ImageOutputStream or writing to it.");
                        e.printStackTrace();
                        return false;
                   // uncomment this code and comment out the 'try-catch' block above
                   // to print to a JFrame instead of to the printer
                   /*          JFrame jf = new JFrame();
                             PaintableJPanel jp = new PaintableJPanel();
                             jp.setImage( img );
                             JScrollPane jsp = new JScrollPane( jp );
                             jf.getContentPane().add( jsp );
                             Insets i = jf.getInsets();
                             jf.setBounds( 0, 0, newX, y );
                             jf.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );
                             jf.setVisible( true );*/
                   return true;
              * Print the document to the specified PrintService.
              * This method cannot tell if the printing was successful. You must register
              * a PrintJobListener
              * @return false if no PrintService is selected in the dialog, true otherwise
              public boolean printDocument(Doc doc, PrintService ps) throws PrintException {
                   if (ps == null)
                   return false;
                   addAllPrintServiceAttributeListeners(ps);
                   DocPrintJob dpj = ps.createPrintJob();
                   addAllPrintJobListeners(dpj);
                   dpj.print(doc, attributes);
                   return true;
              public PrintService showPrintDialog() {
                   return ServiceUI.printDialog(gc, x, y, services, defaultService, flavor, attributes);
              private void addAllPrintServiceAttributeListeners(PrintService ps) {
                   // add all listeners that are currently added to this object
                   for (int i = 0; i < psalListeners.size(); i++) {
                   PrintServiceAttributeListener p = (PrintServiceAttributeListener) psalListeners.get(i);
                   ps.addPrintServiceAttributeListener(p);
              private void addAllPrintJobListeners(DocPrintJob dpj) {
                   // add all listeners that are currently added to this object
                   for (int i = 0; i < pjlListeners.size(); i++) {
                   PrintJobListener p = (PrintJobListener) pjlListeners.get(i);
                   dpj.addPrintJobListener(p);
              // uncomment this also to print to a JFrame instead of a printer
              /* protected class PaintableJPanel extends JPanel {
                   Image img;
                   protected PaintableJPanel() {
                        super();
                   public void setImage( Image i ) {
                        img = i;
                   public void paint( Graphics g ) {
                        g.drawImage( img, 0, 0, this );
    Thanks
    Ram

    Ram,
    I have had printing problems too a year and a half ago. I used all printing apis of java and I still find that it is something java lacks. Now basically you can try autosense. To check whether your printer is capable of printing the docflavor use this PrintServiceLookup.lookupPrintServices(flavor, aset); . If it lists the printer then he can print the document otherwise he can't. I guess that is why you get the error.
    Regards,
    Kevin

  • Trying to pick up the printer

    I have an example below using a simple gui that has print function in it. The aim of the program is when the user clicks on the print button that they can call p the print and print waht ever is in the text area. I'm not sure if i'm in the right forum now so bear with me.
    If any one has any ideas or knows how to fix it theres one error in total on the tool kit, its fairly well commented now so hope fully some one can see the problem is fairly annoying
    Help wold ge great thanking you
    Ambrose
    import java.io.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import java.awt.PrintJob;
    import java.util.List;
    //import sun.tools.javac.Main;
    public class print extends JPanel {
        private JButton jButton14;
        private JTextArea jTextArea1;
        public print() {
            //construct components
            jButton14 = new JButton ("print");
            jTextArea1 = new JTextArea (5, 5);
            //adjust size and set layout
            setPreferredSize (new Dimension (496, 371));
            setLayout (null);
            //add components
            add (jButton14);
            add (jTextArea1);
            //set component bounds (only needed by Absolute Positioning)
            jButton14.setBounds (210, 245, 100, 20);
            jTextArea1.setBounds (25, 55, 435, 160);
         public void jButton14_actionPerformed(ActionEvent e)
              printText(jTextArea1.getText());
    // Draw individual lines from the text onto pages of a new print job
        private void printText(String text)
            PrintJob p = getToolkit().getPrintJob(this, "Print Job", null); // This causes the print dialog box to pop up
            int pageLength = p.getPageDimension().height; // Find out page size
            StringTokenizer theText = // Prepare to break up the text into lines (one line = one token)
                new StringTokenizer(text, "\n", true); // Returns \n tokens too
            Graphics g = null;
            int lineInc = 0;
            int initialYForPage = 0; // y coord of top line on page
            int yMax = pageLength - 100; // y coord of bottom line, allowing for borders of 50 top and bottom
            int x = 0;                // Initial print position
            int y = initialYForPage;
            int pageNumber = 0;
            boolean newPage = true; // To force page layout initialization
            while (theText.hasMoreTokens()) {           // Scan the lines in theText
                if (newPage) { // Start of a page?
                    g = nextPage(p); // Yes, set up new page
                    lineInc = g.getFontMetrics().getHeight(); // The line height in pixels for the current font
                   y = initialYForPage;
                   pageNumber++;
                    g.drawString("Page " + pageNumber, x, y);      // Page number at top
                    y += 2 * lineInc;           // Space for a blank line
                    newPage = false;
                String nextBit = theText.nextToken(); // Get next line or \n if it's an empty line
                if (nextBit.equals("\n")) // End of an empty line?
                    nextBit = ""; // Yes, prepare to output an empty line
                else // No, we got a line
                if (theText.hasMoreTokens()) { // \n following?
              String discard = theText.nextToken(); // Yes, discard the \n following the line
                // System.out.println(nextBit);       // Just to check, during testing
                g.drawString(nextBit, x, y);      // Draw next line
                y += lineInc;     // and move down a bit (x doesn't change: always draw at left)
                if (y > yMax) {      // At end of page?
                    g.dispose();           // Yes, print it
                    newPage = true;      // Force page initialization if there's another page
            if (!newPage)
                g.dispose(); // Print last page, if not already done
            p.end(); // End of print job - phew!
        } // printText
        // Grab a new page for printing on
        private Graphics nextPage(PrintJob p) {
            Graphics g = p.getGraphics();
            g.translate(50, 50); // To move image away from top left of page
            g.setFont(new Font("SansSerif", Font.PLAIN, 10));
            return g;
        } // nextPage
        public static void main (String[] args) {
            JFrame frame = new JFrame ("print");
            frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add (new print());
            frame.pack();
            frame.setVisible (true);
    }

    Sorry the problem was in this line of code it picks up the gettoolkit as an error and when i excute the frame nothing happens
    PrintJob p = getToolkit().getPrintJob(this, "Print Job", null);

  • Need Printing Help (location to top-left?)

    im able to print out a JFrame, no problem..but the onscreen image and whats printed on paper arent exactly the same
    1) Printed is 1.5 - 2X bigger than onscreen (1280x1024 resolution)
    2) Printed starts near the middle of the page, not at the top left hand corner
    public class PrintUtilities implements Printable {
      private Component componentToBePrinted;
      public static void printComponent(Component c) {
        new PrintUtilities(c).print();
      public PrintUtilities(Component componentToBePrinted) {
        this.componentToBePrinted = componentToBePrinted;
      public void print() {
        PrinterJob printJob = PrinterJob.getPrinterJob();
        printJob.setPrintable(this);
        if (printJob.printDialog())
          try {
            printJob.print();
          } catch(PrinterException pe) {
            System.out.println("Error printing: " + pe);
      public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
        if (pageIndex > 0) {
          return(NO_SUCH_PAGE);
        } else {
          Graphics2D g2d = (Graphics2D)g;
          g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());   
          disableDoubleBuffering(componentToBePrinted);
          componentToBePrinted.paint(g2d);
          enableDoubleBuffering(componentToBePrinted);
          return(PAGE_EXISTS);
      /** The speed and quality of printing suffers dramatically if
       *  any of the containers have double buffering turned on.
       *  So this turns if off globally.
       *  @see enableDoubleBuffering
      public static void disableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(false);
      /** Re-enables double buffering globally. */
      public static void enableDoubleBuffering(Component c) {
        RepaintManager currentManager = RepaintManager.currentManager(c);
        currentManager.setDoubleBufferingEnabled(true);
    }by simply calling PrintUtilities.print(myJFrame), it prints. how can i maka the onscreen and the printed page be "exact size" and how can i make it start printing from the top left hand corner?
    thanks
    i tried using myMainPanel.setLocation(0,0); in the gui construction...and also setting g2d.setFont(smallerFont); from PrintUtilities..but doesnt work at all
    any ideas? thanks

    You should change some piece of code ....Just change the part in :
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) {...}
    function.
    1) scale the graphics to see the whole screen on the page
    /**copy this code before
    * "componentToBePrinted.paint(g2d);"
    *line
    Dimension dimension=componentToBePrinted.getSize();
    g2d.scale( 1.0*pageFormat.getWidth()/dimension.width,
    1.0*pageFormat.getHeight()/dimension.height );
    // "1.0*" is for casting to double2) delete the code line :
    g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());to start drawingfrom (0,0) coordinate

  • How to print jEditorPane content

    Hi,
    I have got the html content in jeditorPane and i wanted to print the content to the printer in landscape mode. can any one help me out?, I appreciate your time . Infact i did see an example here but when i started running it, i could end up no where.
    Thanks,
    krishna

    infact the example i saw in this forum, rythos , is the author but i could not make the code he posted there working. I would appreciate if some one can take interest into it.
    Below is the Rythos Code :
    import javax.swing.*;import java.awt.*;import java.awt.image.*;import java.io.*;import java.util.*;import javax.print.*;import javax.print.attribute.*;import javax.print.attribute.standard.*;import javax.print.event.*;import javax.swing.text.*;import javax.imageio.*;import javax.imageio.stream.*;/** * Sets up to easily print HTML documents. It is not necessary to call any of the setter * methods as they all have default values, they are provided should you wish to change * any of the default values.*/public class Printer {     public static int DEFAULT_DPI = 72;     public static float DEFAULT_PAGE_WIDTH_INCH = 8.5f;     public static float DEFAULT_PAGE_HEIGHT_INCH = 11f;     int x = 100;     int y = 80;     GraphicsConfiguration gc;     PrintService[] services;     PrintService defaultService;     DocFlavor flavor;     PrintRequestAttributeSet attributes;     Vector pjlListeners = new Vector();     Vector pjalListeners = new Vector();     Vector psalListeners = new Vector();     public Printer() {          gc = null;          attributes = new HashPrintRequestAttributeSet();          flavor = null;          defaultService = PrintServiceLookup.lookupDefaultPrintService();          services = PrintServiceLookup.lookupPrintServices( flavor, attributes );          // do something with the supported docflavors          DocFlavor[] df = defaultService.getSupportedDocFlavors();          for( int i = 0; i < df.length; i++ )               System.out.println( df.getMimeType() + " " + df[i].getRepresentationClassName() );          // if there is a default service, but no other services          if( defaultService != null && ( services == null || services.length == 0 ) ) {               services = new PrintService[1];               services[0] = defaultService;          }     }     /**     * Set the GraphicsConfiguration to display the print dialog on.     *     * @param gc a GraphicsConfiguration object     */     public void setGraphicsConfiguration( GraphicsConfiguration gc ) {          this.gc = gc;     }     public void setServices( PrintService[] services ) {          this.services = services;     }     public void setDefaultService( PrintService service ) {          this.defaultService = service;     }     public void setDocFlavor( DocFlavor flavor ) {          this.flavor = flavor;     }     public void setPrintRequestAttributes( PrintRequestAttributeSet attributes ) {          this.attributes = attributes;     }     public void setPrintDialogLocation( int x, int y ) {          this.x = x;          this.y = y;     }     public void addPrintJobListener( PrintJobListener pjl ) {          pjlListeners.addElement( pjl );     }     public void removePrintJobListener( PrintJobListener pjl ) {          pjlListeners.removeElement( pjl );     }     public void addPrintServiceAttributeListener( PrintServiceAttributeListener psal ) {          psalListeners.addElement( psal );     }     public void removePrintServiceAttributeListener( PrintServiceAttributeListener psal ) {          psalListeners.removeElement( psal );     }     public boolean printJEditorPane( JEditorPane jep, PrintService ps ) {          if( ps == null || jep == null ) return false;          // get the root view of the preview pane          View rv = jep.getUI().getRootView( jep );          // get the size of the view (hopefully the total size of the page to be printed          int x = ( int ) rv.getPreferredSpan( View.X_AXIS );          int y = ( int ) rv.getPreferredSpan( View.Y_AXIS );          // find out if the print has been set to colour mode          DocPrintJob dpj = ps.createPrintJob();          PrintJobAttributeSet pjas = dpj.getAttributes();          // get the DPI and printable area of the page. use default values if not available          // use this to get the maximum number of pixels on the vertical axis          PrinterResolution pr = ( PrinterResolution ) pjas.get( PrinterResolution.class );          int dpi;          float pageX, pageY;          if( pr != null ) dpi = pr.getFeedResolution( PrinterResolution.DPI );          else dpi = DEFAULT_DPI;          MediaPrintableArea mpa = ( MediaPrintableArea ) pjas.get( MediaPrintableArea.class );          if( mpa != null ) {               pageX = mpa.getX( MediaPrintableArea.INCH );               pageY = mpa.getX( MediaPrintableArea.INCH );          } else {               pageX = DEFAULT_PAGE_WIDTH_INCH;               pageY = DEFAULT_PAGE_HEIGHT_INCH;          }          int pixelsPerPageY = ( int ) ( dpi * pageY );          // make colour true if the user has selected colour, and the PrintService can support colour          boolean colour = pjas.containsValue( Chromaticity.COLOR );          colour = colour & ( ps.getAttribute( ColorSupported.class ) == ColorSupported.SUPPORTED );          // create a BufferedImage to draw on          int imgMode;          if( colour ) imgMode = BufferedImage.TYPE_3BYTE_BGR;          else imgMode = BufferedImage.TYPE_BYTE_GRAY;          BufferedImage img = new BufferedImage( x, y, imgMode );          Graphics myGraphics = img.getGraphics();          myGraphics.setClip( 0, 0, x, y );          myGraphics.setColor( Color.WHITE );          myGraphics.fillRect( 0, 0, x, y );          // call rootView.paint( myGraphics, rect ) to paint the whole image on myGraphics          rv.paint( myGraphics, new Rectangle( 0, 0, x, y ) );           try {               // write the image as a JPEG to the ByteArray so it can be printed                Iterator writers = ImageIO.getImageWritersByFormatName( "jpeg" );               ImageWriter writer = ( ImageWriter ) writers.next();               ByteArrayOutputStream out = new ByteArrayOutputStream();               ImageOutputStream ios = ImageIO.createImageOutputStream( out );               writer.setOutput( ios );               // get the number of pages we need to print this image               int imageHeight = img.getHeight();               int numberOfPages = ( int ) ( ( imageHeight / pixelsPerPageY ) + 0.5 );               // print each page               for( int i = 0; i < numberOfPages; i++ ) {                    int startY = i * pixelsPerPageY;                                        // get a subimage which is exactly the size of one page                    BufferedImage subImg = img.getSubimage( 0, startY, x, pixelsPerPageY );                    writer.write( subImg );                    SimpleDoc sd = new SimpleDoc( out.toByteArray(), DocFlavor.BYTE_ARRAY.JPEG, null );                    printDocument( sd, ps );                    // reset the ByteArray so we can start the next page                    out.reset();               }          } catch( PrintException e ) {               System.out.println( "Error printing document." );               e.printStackTrace();               return false;          } catch( IOException e ) {               System.out.println( "Error creating ImageOutputStream or writing to it." );               e.printStackTrace();               return false;          }          // uncomment this code and comment out the 'try-catch' block above          // to print to a JFrame instead of to the printer/*          JFrame jf = new JFrame();          PaintableJPanel jp = new PaintableJPanel();          jp.setImage( img );          JScrollPane jsp = new JScrollPane( jp );          jf.getContentPane().add( jsp );          Insets i = jf.getInsets();          jf.setBounds( 0, 0, newX, y );          jf.setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE );          jf.setVisible( true );*/          return true;     }     /**     * Print the document to the specified PrintService.     * This method cannot tell if the printing was successful. You must register     * a PrintJobListener      *     * @return false if no PrintService is selected in the dialog, true otherwise     */     public boolean printDocument( Doc doc, PrintService ps ) throws PrintException {          if( ps == null ) return false;          addAllPrintServiceAttributeListeners( ps );          DocPrintJob dpj = ps.createPrintJob();          addAllPrintJobListeners( dpj );          dpj.print( doc, attributes );          return true;     }     public PrintService showPrintDialog() {          return ServiceUI.printDialog(                gc, x, y, services, defaultService, flavor, attributes );     }     private void addAllPrintServiceAttributeListeners( PrintService ps ) {          // add all listeners that are currently added to this object           for( int i = 0; i < psalListeners.size(); i++ ) {               PrintServiceAttributeListener p = ( PrintServiceAttributeListener ) psalListeners.get( i );               ps.addPrintServiceAttributeListener( p );          }     }     private void addAllPrintJobListeners( DocPrintJob dpj ) {          // add all listeners that are currently added to this object           for( int i = 0; i < pjlListeners.size(); i++ ) {               PrintJobListener p = ( PrintJobListener ) pjlListeners.get( i );               dpj.addPrintJobListener( p );          }     }     // uncomment this also to print to a JFrame instead of a printer/*     protected class PaintableJPanel extends JPanel {          Image img;          protected PaintableJPanel() {               super();          }          public void setImage( Image i ) {               img = i;          }                    public void paint( Graphics g ) {               g.drawImage( img, 0, 0, this );                         }     }*/}

  • Picking up a printer from a gui

    Morning guys
    I have an example below using a simple gui that has print function in it. The aim of the program is when the user clicks on the print button that they can call p the print and print waht ever is in the text area. I'm not sure if i'm in the right forum now so bear with me.
    If any one has any ideas or knows how to fix it theres three errors in total
    Help wold ge great thenking you
    Ambrose
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import java.awt.PrintJob;
    public class print extends JPanel {
        private JButton jButton14;
        private JTextArea jTextArea1;
        public print() {
            //construct components
            jButton14 = new JButton ("print");
            jTextArea1 = new JTextArea (5, 5);
            //adjust size and set layout
            setPreferredSize (new Dimension (496, 371));
            setLayout (null);
            //add components
            add (jButton14);
            add (jTextArea1);
            //set component bounds (only needed by Absolute Positioning)
            jButton14.setBounds (210, 245, 100, 20);
            jTextArea1.setBounds (25, 55, 435, 160);
         public void jButton14_actionPerformed(ActionEvent e) {
    printText(jTextArea1.getText());
    // Draw individual lines from the text onto pages of a new print job
        private void printText(String text) {
            PrintJob p = getToolkit().getPrintJob(this, "Print Job", null); // This causes the print dialog box to pop up
            int pageLength = p.getPageDimension().height; // Find out page size
            StringTokenizer theText = // Prepare to break up the text into lines (one line = one token)
                new StringTokenizer(text, "\n", true); // Returns \n tokens too
            Graphics g = null;
            int lineInc = 0;
            int initialYForPage = 0; // y coord of top line on page
            int yMax = pageLength - 100; // y coord of bottom line, allowing for borders of 50 top and bottom
            int x = 0;                // Initial print position
            int y = initialYForPage;
            int pageNumber = 0;
            boolean newPage = true; // To force page layout initialization
            while (theText.hasMoreTokens()) {           // Scan the lines in theText
                if (newPage) { // Start of a page?
                    g = nextPage(p); // Yes, set up new page
                    lineInc = g.getFontMetrics().getHeight(); // The line height in pixels for the current font
                   y = initialYForPage;
                   pageNumber++;
                    g.drawString("Page " + pageNumber, x, y);      // Page number at top
                    y += 2 * lineInc;           // Space for a blank line
                    newPage = false;
                String nextBit = theText.nextToken(); // Get next line or \n if it's an empty line
                if (nextBit.equals("\n")) // End of an empty line?
                    nextBit = ""; // Yes, prepare to output an empty line
                else // No, we got a line
                if (theText.hasMoreTokens()) { // \n following?
              String discard = theText.nextToken(); // Yes, discard the \n following the line
                // System.out.println(nextBit);       // Just to check, during testing
                g.drawString(nextBit, x, y);      // Draw next line
                y += lineInc;     // and move down a bit (x doesn't change: always draw at left)
                if (y > yMax) {      // At end of page?
                    g.dispose();           // Yes, print it
                    newPage = true;      // Force page initialization if there's another page
            if (!newPage)
                g.dispose(); // Print last page, if not already done
            p.end(); // End of print job - phew!
        } // printText
        // Grab a new page for printing on
        private Graphics nextPage(PrintJob p) {
            Graphics g = p.getGraphics();
            g.translate(50, 50); // To move image away from top left of page
            g.setFont(new Font("SansSerif", Font.PLAIN, 10));
            return g;
        } // nextPage
        public static void main (String[] args) {
            JFrame frame = new JFrame ("print");
            frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add (new print());
            frame.pack();
            frame.setVisible (true);
    }

    The iPhone has never had the ability to do what you are trying to describe. You can select Call Forwarding, which will make all calls normally coming to the iPhone ring to another number of your choosing. But your iPhone does not ring at all when you are forwarding calls.
    Same thing with Call Forwarding from your home phone. I have Qwest at home - when I have call forwarding active there, the phone rings once and then stops, just to remind you that you have forwarding active, but you can't pick up a call there - it immediately forwards to the number of your choice - like your mobile or whatever.
    You need GrandCentral or Vonage simulring to ring a call at multiple places. Do a search, there have been discussions of these services on here before.

  • JNI - How to use the error reporting mechanism?

    I've developed a C++ DLL which is loaded from a commercial Win32 application (not written by me) as a plug-in for external calculations. On its initialization the C++ DLL launches the Java VM via the JNI invocation interface. When the DLL functions are called by the application, they forward the calls to Java objects inside the Java VM, again via JNI invocation interface.
    This works well, but I have encountered a weird error.
    From Java I open a JFrame containing a JTextArea as small console for debug output messages. If I turn output to this debug console off (my printToConsole routine checks whether a boolean flag is set), the string concatenation operator may lead to a crash of the Java VM.
    For example, if in one of the Java functions called from the
    DLL via JNI invocation interface the following is the first statement,
    it leads to a crash of the Java VM and the application that loaded the C++ proxy DLL.
    String test=""+Math.random(); // String test not used later
    Interestingly, if I comment this statement out, the Java code works fine WITHOUT any crash. I've already thought about potential races and synchronization issues in my code, but I don't see where this is the case. And the string concatenation error fails as well, if I insert sleep() statements in front of it and at other places in the code. However, if I turn on log messages printed to my JFrame debug console (containing a JTextArea), the String concatenation works without problems.
    So maybe the JNI interface has a bug and affects the Java VM; I don't see where my JNI code is wrong.
    One problem is that I do not get any stdout output, as the C++ proxy DLL is loaded by the Windows application, even if I start the Windows application from the DOS command line (under Windows).
    Does anyone know how to use the error reporting mechanism?
    http://java.sun.com/j2se/1.4.2/docs/guide/vm/error-handling.html
    Is it possible that the JVM, when it crashes, writes debug information about the crash into a file instead of stdout/stderr?
    My C++ proxy DLL was compiled in debug mode, but the commercial application (which loaded the DLL) is very likely not.
    I do not know hot to find the reason why the String concatenation fails inside the Java function called from the C++ DLL via JNI.

    Yes, I've initially thought about errors in the C++ code too. But the C++ code is actually very simple and short. It doesn't allocate anything on the C++ side. It allocates a couple of ByteBuffers inside the Java VM however via JNI invocation interface calls of env->NewDirectByteBuffer(). The native memory regions accessed via the ByteBuffers are allocated not by my own C++ code, but by the program that calls my DLL (the program is Metastock).
    The interesting thing is that everything works fine if output to my debug console is enabled, which means that in the Java print routine getConsoleLoggingState() returns true and text is appended to the jTextArea.
    static synchronized void print(String str)
    { MetaStockMonitor mMon=getInstance();
    if ( mMon.getFileLoggingState() && mMon.logFileWriter!=null) {
    mMon.logFileWriter.print(str);
    mMon.logFileWriter.flush();
    if ( mMon.getConsoleLoggingState() ) {
    mMon.jTextArea1.append(str);
    Only if output to the JTextArea is turned off (ie. getConsoleLoggingState()==false), the crash happens when the FIRST statement in the Java routine called via JNI invocation interface is a (useless) String concatenation operation, as described above.
    String test=""+Math.random(); // String test not used later
    Moreover, the crash happens BEFORE the allocated ByteBuffer objects are accessed in the Java code. But again, if console output is turned on, it works stable. If console output is turned off, it works when the (useless) String concatenation operation is removed in the Java routine called from C++.
    I've already thought about potential races (regarding multiple threads), but this can be ruled out in my case. It almost appears as if the JVM can have problems when called by the invocation interface (I tested it with Java 1.4.2 b28).
    All the calls between C++ and Java go ALWAYS in the direction from C++ code to Java. Unfortunately, there is no special JRE version with extensive logging capabilities to facilitate debugging. And the problem is not easily reproducible either.
    JNIEnv* JNI_GetEnv()
    JNIEnv *env;
    cached_jvm->AttachCurrentThread((void**)&env,NULL);
    fprintf(logfile,"env=%i\n",env);
    fflush(logfile);
    return env;
    // function called by Metastock's MSX plug-in interface
    BOOL __stdcall createIndEngine (const MSXDataRec *a_psDataRec,
    const MSXDataInfoRecArgsArray *a_psDataInfoArgs,
    const MSXNumericArgsArray *a_psNumericArgs,
    const MSXStringArgsArray *a_psStringArgs,
    const MSXCustomArgsArray *a_psCustomArgs,
    MSXResultRec *a_psResultRec)
    a_psResultRec->psResultArray->iFirstValid=0;
    a_psResultRec->psResultArray->iLastValid=-1;
    jthrowable ex;
    jmethodID mid;
    JNIEnv* env=JNI_GetEnv();
    jobject chart=getChart(env, a_psDataRec);
    if ( chart==NULL) {
    return MSX_ERROR;
    jobject getChart (JNIEnv* env, const MSXDataRec *a_psDataRec)
    jthrowable ex;
    jmethodID mid;
    int closeFirstValid, closeLastValid;
    closeFirstValid=a_psDataRec->sClose.iFirstValid;
    closeLastValid=a_psDataRec->sClose.iLastValid;
    long firstDate, firstTime;
    if (closeFirstValid>=1 && closeFirstValid<=closeLastValid) {
    firstDate = a_psDataRec->psDate[closeFirstValid].lDate;
    firstTime = a_psDataRec->psDate[closeFirstValid].lTime;
    } else {
    firstDate=0;
    firstTime=0;
    jclass chartFactoryClass = env->FindClass("wschwendt/metastock/msx/ChartFactory");
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot find class ChartFactory\n");
    printSBufViaJava(sbuf);
    return NULL;
    mid = env->GetStaticMethodID(chartFactoryClass, "getInstance", "()Lwschwendt/metastock/msx/ChartFactory;");
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot find method ID for ChartFactory.getInstance()\n");
    printSBufViaJava(sbuf);
    return NULL;
    jobject chartFactory=env->CallStaticObjectMethod(chartFactoryClass, mid);
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Exception while calling ChartFactory.getInstance()");
    printSBufViaJava(sbuf);
    return NULL;
    mid = env->GetMethodID(chartFactoryClass, "getChartID", "(Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;Ljava/nio/ByteBuffer;IIIIIII)F");
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot find method ID for ChartFactory.getChartID()\n");
    printSBufViaJava(sbuf);
    return NULL;
    jobject symbolBuf=env->NewDirectByteBuffer(a_psDataRec->pszSymbol, strlen(a_psDataRec->pszSymbol) );
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot allocate symbolBuf\n");
    printSBufViaJava(sbuf);
    return NULL;
    jobject securityNameBuf=env->NewDirectByteBuffer(a_psDataRec->pszSecurityName, strlen(a_psDataRec->pszSecurityName) );
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot allocate securityNameBuf\n");
    printSBufViaJava(sbuf);
    return NULL;
    jobject securityPathBuf=env->NewDirectByteBuffer(a_psDataRec->pszSecurityPath, strlen(a_psDataRec->pszSecurityPath) );
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot allocate securityPathBuf\n");
    printSBufViaJava(sbuf);
    return NULL;
    jobject securityOnlineSourceBuf=env->NewDirectByteBuffer(a_psDataRec->pszOnlineSource, strlen(a_psDataRec->pszOnlineSource) );
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Cannot allocate onlineSourceBuf\n");
    printSBufViaJava(sbuf);
    return NULL;
    // Java Function call leads to crash, if console output is turned off and
    // the first statement in the Java routine is a (useless) string concatenation.
    // Otherwise it works stable.
    jfloat chartID=env->CallFloatMethod(chartFactory, mid, securityNameBuf, symbolBuf,
    securityPathBuf, securityOnlineSourceBuf, (jint)(a_psDataRec->iPeriod),
    (jint)(a_psDataRec->iInterval), (jint)(a_psDataRec->iStartTime),
    (jint)(a_psDataRec->iEndTime), (jint)(a_psDataRec->iSymbolType),
    (jint)firstDate, (jint)firstTime );
    if (ex= env->ExceptionOccurred() ) {
    env->ExceptionDescribe();
    env->ExceptionClear();
    sprintf(sbuf, "DLL: Exception while calling ChartFactory.getChartID()");
    printSBufViaJava(sbuf);
    return NULL;

Maybe you are looking for

  • Safari won't load pages from search results

    Weird problem.  Using Safari 8.0.3, I do a search using www.google.com or just search in the address bar.  Google returns the results, no problem.  However, if I try to follow a link by clicking on it, Safari will seemingly try to load it for a while

  • IPhone 2.0 Bluetooth with RSAP for VW car kit ?

    Does anyone knows if this new iphone comes with RSAP in bluetooth that allows you to connect with VW PASSAT and others that only support RSAP protocol ? Also is there any way to get iPhone to download photos from a Canon 20D ? I can get my ipod video

  • Patch for 4.7ee

    hi all , well am working on 4.7ee , sales & distribution module. I was informed to apply patch for flow of data into ecxise invoice(thats tax determination for india). can any one let me know "PATCH LEVEL SHOULD BE UPGRADED TO ? THANKS. JERRY

  • Drill down in the esssbase outline

    Looks like this is the true essbase knowledge base forum. I am experiencing a prob that I am hoping that someone has the answer to: There is a long long delay when I attempt to drill down in my outline. The outline is relatively small (a few hundred

  • My MacBook trackpad has stopped working correctly and now my MacBook Pro is beginning to malfunction

    yesterday my MacBook trackpad stopped working, after resetting my mac it began working again but was jumpy. Now a day later when I turn my laptop on the mouse works for a short while (maybe 4 minutes) and then begins to go jumpy again and then my scr