Results 1 to 5 of 5
Like Tree1Likes
  • 1 Post By kaydell2

Thread: java code does not do anything

  1. #1
    west-wot is offline Member
    Join Date
    Dec 2012
    Posts
    16
    Rep Power
    0

    Default java code does not do anything

    Hi all i have the code below, it complies just fine, no errors but it does not do anything, what it is meant to is print out a page saying

    hello world
    have a nice day

    but nothing happens, what am i doing wrong ?

    code :

    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    /**
     *
     * @author Richard
     */
    import java.io.*;
    import javax.print.*;
    import javax.print.attribute.*;
    import javax.print.attribute.standard.*;
    import javax.print.event.*;
    
    public class printtest {
        public static void main(String[] args) {
            try {
                // Open the image file
                
                String testData = "hello world \r\n have a nice day.";
                InputStream is = new ByteArrayInputStream(testData.getBytes());
                DocFlavor flavor =  DocFlavor.INPUT_STREAM.AUTOSENSE   ;
    
                
                //DocFlavor flavor = DocFlavor.STRING.TEXT_PLAIN;     
                //DocFlavor flavor = DocFlavor.CHAR_ARRAY.TEXT_PLAIN;
                
                // Find the default service
                
                PrintService service = PrintServiceLookup.lookupDefaultPrintService();
                System.out.println(service);
                
                // Create the print job
                DocPrintJob job = service.createPrintJob();
                Doc doc= new SimpleDoc(is, flavor, null);
                
                PrintJobWatcher pjDone = new PrintJobWatcher(job);
               
                // Print it
                job.print(doc, null);
                
                pjDone.waitForDone();
    
                // It is now safe to close the input stream
                is.close();
    
      
            } catch (PrintException e) {
                System.out.println("print exception");
                System.out.println(e.getMessage());
            } catch (IOException e) {
                System.out.println("IO exception");
                e.printStackTrace();
            }
    
        }
    
        static class PrintJobWatcher {
            // true iff it is safe to close the print job's input stream
            boolean done = false;
    
            PrintJobWatcher(DocPrintJob job) {
                // Add a listener to the print job
                job.addPrintJobListener(new PrintJobAdapter() {
                    public void printJobCanceled(PrintJobEvent pje) {
                        allDone();
                    }
                    public void printJobCompleted(PrintJobEvent pje) {
                        allDone();
                    }
                    public void printJobFailed(PrintJobEvent pje) {
                        allDone();
                    }
                    public void printJobNoMoreEvents(PrintJobEvent pje) {
                        allDone();
                    }
                    void allDone() {
                        synchronized (PrintJobWatcher.this) {
                            done = true;
                            PrintJobWatcher.this.notify();
                        }
                    }
                });
            }
            public synchronized void waitForDone() {
                try {
                    while (!done) {
                        wait();
                    }
                } catch (InterruptedException e) {
                }
            }
        }
    
    }

  2. #2
    west-wot is offline Member
    Join Date
    Dec 2012
    Posts
    16
    Rep Power
    0

    Default Re: java code does not do anything

    sorry it was my fault for being new to java

    i am currently using bluej


    i have just done void main( String[] args) printtest.main ({})

    and it comes up with a window displaying :

    Win32 Printer : HP988FD1 (HP Officejet Pro 8600) print exception Printer is not accepting job.

    EDIT

    edit since then i am only getting a window appearing saying : Win32 Printer : HP Deskjet F4200 series and nothing else happens or is said

    EDIT 2:

    i have noticed that the print job goes into the print queue for a split second and then vanishes, it does not print anything out still and no errors, any ideas ?

    EDIT 3:

    this issue is not the printer or driver or anything, as using the code below i was able to send a java file to print, so now im really confused :
    Java Code:
    import java.awt.*;
    import java.awt.font.*;
    import java.awt.geom.*;
    import java.awt.print.*;
    import java.text.*;
    /**
    * The PrintText application expands on the
    * PrintExample application in that it images
    * text on to the single page printed.
    */
    public class PrintText implements Printable {
    /**
    * The text to be printed.
    */
    private static final String mText = 
    "Four score and seven years ago our fathers brought forth on this "
    + "continent a new nation, conceived in liberty and dedicated to the "
    + "proposition that all men are created equal. Now we are engaged in "
    + "a great civil war, testing whether that nation or any nation so "
    + "conceived and so dedicated can long endure. We are met on a great "
    + "battlefield of that war. We have come to dedicate a portion of "
    + "that field as a final resting-place for those who here gave their "
    + "lives that that nation might live. It is altogether fitting and "
    + "proper that we should do this. But in a larger sense, we cannot "
    + "dedicate, we cannot consecrate, we cannot hallow this ground." 
    + "The brave men, living and dead who struggled here have consecrated "
    + "it far above our poor power to add or detract. The world will "
    + "little note nor long remember what we say here, but it can never "
    + "forget what they did here. It is for us the living rather to be "
    + "dedicated here to the unfinished work which they who fought here "
    + "have thus far so nobly advanced. It is rather for us to be here "
    + "dedicated to the great task remaining before us--that from these "
    + "honored dead we take increased devotion to that cause for which "
    + "they gave the last full measure of devotion--that we here highly "
    + "resolve that these dead shall not have died in vain, that this "
    + "nation under God shall have a new birth of freedom, and that "
    + "government of the people, by the people, for the people shall "
    + "not perish from the earth.";
    /**
    * Our text in a form for which we can obtain a
    * AttributedCharacterIterator.
    */
    private static final AttributedString mStyledText = new AttributedString(mText);
    /**
    * Print a single page containing some sample text.
    */
    static public void main(String args[]) {
    /* Get the representation of the current printer and 
    * the current print job.
    */
    PrinterJob printerJob = PrinterJob.getPrinterJob();
    /* Build a book containing pairs of page painters (Printables)
    * and PageFormats. This example has a single page containing
    * text.
    */
    Book book = new Book();
    book.append(new PrintText(), new PageFormat());
    /* Set the object to be printed (the Book) into the PrinterJob.
    * Doing this before bringing up the print dialog allows the
    * print dialog to correctly display the page range to be printed
    * and to dissallow any print settings not appropriate for the
    * pages to be printed.
    */
    printerJob.setPageable(book);
    /* Show the print dialog to the user. This is an optional step
    * and need not be done if the application wants to perform
    * 'quiet' printing. If the user cancels the print dialog then false
    * is returned. If true is returned we go ahead and print.
    */
    boolean doPrint = printerJob.printDialog();
    if (doPrint) {
    try {
    printerJob.print();
    } catch (PrinterException exception) {
    System.err.println("Printing error: " + exception);
    }
    }
    }
    /**
    * Print a page of text.
    */
    public int print(Graphics g, PageFormat format, int pageIndex) {
    /* We'll assume that Jav2D is available.
    */
    Graphics2D g2d = (Graphics2D) g;
    /* Move the origin from the corner of the Paper to the corner
    * of the imageable area.
    */
    g2d.translate(format.getImageableX(), format.getImageableY());
    /* Set the text color.
    */
    g2d.setPaint(Color.black);
    /* Use a LineBreakMeasurer instance to break our text into
    * lines that fit the imageable area of the page.
    */
    Point2D.Float pen = new Point2D.Float();
    AttributedCharacterIterator charIterator = mStyledText.getIterator();
    LineBreakMeasurer measurer = new LineBreakMeasurer(charIterator, g2d.getFontRenderContext());
    float wrappingWidth = (float) format.getImageableWidth();
    while (measurer.getPosition() < charIterator.getEndIndex()) {
    TextLayout layout = measurer.nextLayout(wrappingWidth);
    pen.y += layout.getAscent();
    float dx = layout.isLeftToRight()? 0 : (wrappingWidth - layout.getAdvance());
    layout.draw(g2d, pen.x + dx, pen.y);
    pen.y += layout.getDescent() + layout.getLeading();
    }
    return Printable.PAGE_EXISTS;
    }
    }

    BUT

    the code below does not work, no error messages, even says printing done..... in the terminal, can see this job once again in the queue but never prints out anything

    Java Code:
    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.File;
    import java.io.FileInputStream;
    
    import javax.print.Doc;
    import javax.print.DocFlavor;
    import javax.print.DocPrintJob;
    import javax.print.PrintException;
    import javax.print.PrintService;
    import javax.print.PrintServiceLookup;
    import javax.print.SimpleDoc;
    
    import javax.print.attribute.HashPrintRequestAttributeSet;
    import javax.print.attribute.PrintRequestAttributeSet;
    import javax.print.attribute.standard.Copies;
    
    import javax.print.event.PrintJobAdapter;
    import javax.print.event.PrintJobEvent;
    
    public class PrintTextFile {
    
      public static void main(String[] args) throws PrintException, IOException {
        String defaultPrinter =
          PrintServiceLookup.lookupDefaultPrintService().getName();
        System.out.println("Default printer: " + defaultPrinter);
    
        PrintService service = PrintServiceLookup.lookupDefaultPrintService();
    
        FileInputStream in = new FileInputStream(new File("D:/Documents/testDocToPrintUsingJava.txt"));
    
        PrintRequestAttributeSet  pras = new HashPrintRequestAttributeSet();
        pras.add(new Copies(1));
    
    
        DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
        Doc doc = new SimpleDoc(in, flavor, null);
    
        DocPrintJob job = service.createPrintJob();
        PrintJobWatcher pjw = new PrintJobWatcher(job);
        job.print(doc, pras);
        pjw.waitForDone();
        in.close();
    
        // send FF to eject the page
        InputStream ff = new ByteArrayInputStream("\f".getBytes());
        Doc docff = new SimpleDoc(ff, flavor, null);
        DocPrintJob jobff = service.createPrintJob();
        pjw = new PrintJobWatcher(jobff);
        jobff.print(docff, null);
        pjw.waitForDone();
      }
    }
    
    class PrintJobWatcher {
      boolean done = false;
    
      PrintJobWatcher(DocPrintJob job) {
        job.addPrintJobListener(new PrintJobAdapter() {
          public void printJobCanceled(PrintJobEvent pje) {
            allDone();
          }
          public void printJobCompleted(PrintJobEvent pje) {
            allDone();
          }
          public void printJobFailed(PrintJobEvent pje) {
            allDone();
          }
          public void printJobNoMoreEvents(PrintJobEvent pje) {
            allDone();
          }
          void allDone() {
            synchronized (PrintJobWatcher.this) {
              done = true;
              System.out.println("Printing done ...");
              PrintJobWatcher.this.notify();
            }
          }
        });
      }
      public synchronized void waitForDone() {
        try {
          while (!done) {
            wait();
          }
        } catch (InterruptedException e) {
        }
      }
    }
    Last edited by west-wot; 12-21-2012 at 02:52 AM.

  3. #3
    kaydell2 is offline Senior Member
    Join Date
    Dec 2012
    Posts
    107
    Rep Power
    0

    Default Re: java code does not do anything

    I tried to compile your code, but the code for the Book class was missing. Will you post that?
    Fubarable likes this.

  4. #4
    west-wot is offline Member
    Join Date
    Dec 2012
    Posts
    16
    Rep Power
    0

    Default Re: java code does not do anything

    above is the exact code as i have got and complied

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: java code does not do anything

    Quote Originally Posted by west-wot View Post
    above is the exact code as i have got and complied
    Well, then I guess about all we can do is wish you much luck and success with this problem and this project. Please feel free to post your Book class however if you need our help.

Similar Threads

  1. Replies: 16
    Last Post: 01-31-2012, 08:36 PM
  2. Translate Vb.net code into Java code
    By Radu in forum New To Java
    Replies: 5
    Last Post: 04-12-2011, 09:27 AM
  3. Replies: 0
    Last Post: 02-21-2011, 11:50 AM
  4. Convert java code to midlet code
    By coldvoice05 in forum New To Java
    Replies: 1
    Last Post: 08-12-2009, 11:14 AM
  5. Convert java code to midlet code
    By coldvoice05 in forum Advanced Java
    Replies: 1
    Last Post: 08-09-2009, 01:21 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •