1 Reply Latest reply on Dec 3, 2008 9:24 PM by 843810

    Questions About Printing

      Hi, i am currently having problems with using java print .
      What i need is selecting the printer without using a popup dialog by parsing in a string hardcoded which i would implement a registry reader that would take in the printer name and use that specific printer to read, however i am clueless to edit the codes i had done, by using JobAttributes? or others . please help :=) thankx
      belows are my current codes
      package javaapplication1;
      import java.awt.*;
      import java.awt.event.*;
      import java.awt.print.*;
      import java.io.*;
      import java.util.*;
      import java.util.logging.Level;
      import java.util.logging.Logger;
      import javax.swing.*;
      import javax.swing.filechooser.*;
      import javax.print.*;
      import java.awt.JobAttributes.*;
      public class PrintSample  implements Printable {
         static JTextArea textarea = new JTextArea(10,40);
         static JFrame   window = new JFrame("Fax Services");
         String filename;
        public static  void main(String args[])   {
           final JFileChooser fc;
           fc = new JFileChooser();
           JButton openButton = new JButton("Open");
          final Container cp = window.getContentPane();
          JButton buttonPJ = new JButton("Use Printable");
          LayoutManager lm = new FlowLayout(FlowLayout.CENTER, 20,20);
          // fill in text to display (and later print)
           // set up layout and fill in sample
           cp.add(new JScrollPane(textarea));
           // add the button press response for buttons
       openButton.addActionListener(new ActionListener(){
           public void actionPerformed(ActionEvent e){
             int ret=fc.showOpenDialog(cp);
             FileInputStream filein = null;
                          try {
                              java.io.File file = fc.getSelectedFile();
                              filein = new java.io.FileInputStream(file);
                              int x = filein.available();
                              byte b[]=new byte[x];
                              String content = new String(b);
                          } catch (FileNotFoundException ex) {
                              Logger.getLogger("global").log(Level.SEVERE, null, ex);
                          } catch(IOException ex2){
                              Logger.getLogger("global").log(Level.SEVERE, null, ex2);
                          }finally {
                              try {
                              } catch (IOException ex) {
                                  Logger.getLogger("global").log(Level.SEVERE, null, ex);
                 textarea.append("Errors Occur");
       }      }); 
           buttonPJ.addActionListener(new ActionListener() {
              public void actionPerformed(ActionEvent e) {
           // set up WindowListener to close the program
           window.addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
          window.setVisible(true);                  // frame starts out invisible
         // PrinterJob implementation
         static void printPrinterJob() {
            PrinterJob printerjob = PrinterJob.getPrinterJob();
            // set the characteristics of 
            // the job to be printed - use setPageable and book if
            // outputing a document. Use setPrintable for "simple" printing - all pages formatted the same
            printerjob.setPrintable(new PrintSample());
            try {
                //JobAttributes j = new JobAttributes();
               printerjob.print();            // print the page(s)  (this method with call the page painters)
            } catch (PrinterException exception) {
               System.err.println("Printing error: " + exception);
         // print  - draw the page
         // Parameters:    graphics - context in which to draw the page
         //                pageFormat - size and orientation of page being drawn
         //               pageIndex - zero-based index position of the  page in the print job
         public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
            throws PrinterException {
             String strText =null;    // text string to output
            int lineStart;           // start index of line in textarea
             int lineEnd;             // end index of line in textarea
             int lineNumber;          // current line in textarea
             int lineCount;           // total number of lines in textarea
             if (pageIndex >= 1 ) return Printable.NO_SUCH_PAGE;
             // move the drawing origin to the imageable area ( makes sure its drawn where the printer can )
             graphics.translate((int)(pageFormat.getImageableX()), (int)(pageFormat.getImageableY()));
             // get the text from the textarea one line at a time
             lineNumber = 0;
             lineCount = textarea.getLineCount();
             strText = textarea.getText();
             while (lineNumber < lineCount) {
                try {
                   lineStart = textarea.getLineStartOffset(lineNumber);
                   lineEnd = textarea.getLineEndOffset(lineNumber);
                   strText = textarea.getText(lineStart, lineEnd-lineStart);
                } catch( Exception exception) {
                   System.out.println("Printing error:" + exception);                  // have to catch BadLocationException
                // determine drawing location of each successive line
                graphics.drawString(strText,0,(lineNumber + 1) *20);
                lineNumber = lineNumber + 1;
              return Printable.PAGE_EXISTS;                      // page was drawn successfully (return NO_SUCH_PAGE if not)
        • 1. Re: Questions About Printing
          Since JTextArea is a descendant of JTextComponent all you need is :

          java.text.MessageFormat header = null; // header to print null or text
          java.text.MessageFormat footer = null; // footer to print null or text
          boolean showPrintDialog = true; // display the print dialog true || false
          javax.print.PrintService service = javax.print.PrintServiceLookup.lookupDefaultPrintService();
          javax.print.attribute.PrintRequestAttributeSet attributes = null;
          boolean interactive = true;
          jTextComponent.print(header, footer, showPrintDialog, service, attributes, interactive);

          you can put this into a separate thread so it doesn't stall the application
          or inside your printPrinterJob method, discard the overwritten print method
          and let JTextComponent do the print handling for you.
          (print method is inherited for most swing components such as JTextArea etc, look in the API)