🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: borland.public.jbuilder.java.language
Article #17085

sample print class w/questions...

#17085
From: Ross Dukeshier
Date: Sat, 19 Dec 1998 00:00
255 lines
9381 bytes
I think I understand most of how the new JDK 1.2 print stuff is supposed to
work, but I have some questions.

1) Why wouldn't the Book class be made Printable?  It seems like it should
as the print method the Printable interface expects you to implement accepts
a pageIndex as a parameter.  If anyone has any thoughts as to why, I'd love
to hear them.  Anyway, with that thought in mind, I wrote up the class below
in an attempt to make it so.

As you can see, the constructor accepts a vector of text - the idea being
this is a record formatted report where each element of the vector is a line
of text for a single record.

There are some problems with it - hence the reason for me posting this to
the newsgroup.  First, I needed to get a Graphics object so I could write
the text to it but I haven't been able to find anything other than the
PrintJob class (and components) to give it to me.  If I use PrintJob, when
the constructor finishes and tries to print, the printer is already taken by
the PrintJob object that gave me the graphics object.  So, first question -
how do I get the graphics object for printing using the PrinterJob class?
Should I instead store the frame as an attribute and get it from that?

Second, you'll notice that when I try to add a page to the book, I have to
provide a Printable object.  Since the only object I have that's printable
is the PrinterBook itself, I pass it.  This doesn't seem right to me.  If
I'm adding a page to a book, shouldn't the page be Printable?  And, if the
page is Printable, then what does it mean when I pass the pageIndex to the
print method it would have to implement?  Something seems wrong here...

Anyway, here's the code, if you have any comments or suggestions, please
provide them.



package cm;

import java.io.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.font.*;
import java.text.*;
import java.util.*;
import java.awt.print.*;
import java.awt.geom.*;
import javax.swing.*;

public class PrintableBook extends Writer implements Printable {

  protected String time;
  protected Font font;
  protected int fontsize;
  protected Font headerfont;
  protected LineMetrics metrics;
  protected LineMetrics headermetrics;
  protected double x0;
  protected double y0;
  protected double headery;
  protected int linesperpage;
  protected int charnum = 0;
  protected int linenum = 0;
  protected int pagenum = 0;
  protected PrinterJob job;
  protected PrintJob pj;
  protected Book book;
  protected Graphics2D page;
  protected PageFormat pageFormat;

  public PrintableBook(Frame frame, Font font, Vector text, PageFormat
pageFormat) {
    try {
      System.out.println("Creating book");
      GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
      PrinterJob job = PrinterJob.getPrinterJob();

      System.out.println("Getting time");
      DateFormat df = DateFormat.getDateTimeInstance(DateFormat.LONG,
DateFormat.SHORT);
      df.setTimeZone(TimeZone.getDefault());
      time = df.format(new Date());

      System.out.println("Setting page format");
      this.pageFormat = pageFormat;

      System.out.println("Determining lines per page");
      fontsize = font.getSize();
      System.out.println(font.getSize());
      double ih = pageFormat.getImageableHeight();
      System.out.println(ih);
      metrics = font.getLineMetrics("Test", 0, 4, new
FontRenderContext(null,false,false));

      linesperpage = (int)
(pageFormat.getImageableHeight()/metrics.getHeight());
      System.out.println(linesperpage);

      //*******QUESTION HERE
      Toolkit tk = Toolkit.getDefaultToolkit();
      System.out.println("Getting graphics object");
      pj = tk.getPrintJob(frame,job.getJobName(), new Properties());
      //page = (Graphics2D) pj.getGraphics();
      page = (Graphics2D) frame.getGraphics();
      page.setColor(Color.black);
      System.out.println("Creating book");
      book = new Book();
      System.out.println("Adding first page to book");
      //******AND HERE
      book.append(this, pageFormat);
      System.out.println("Writing text to book");
      String line;
      for (int row=0; row < text.size(); row++) {
        line = (String) text.elementAt(row);
        System.out.println(line);
        write(line.toCharArray(),0,line.length());
      }
      job.print();
    }
    catch (Exception e) {
      System.out.println("Error occurred");
      System.out.println(e.getMessage());
    }
  }

  public void write(char[] buffer, int index, int len) {
    System.out.println("In write method");
    synchronized(this.lock) {
      page.drawChars(buffer, index, len, (int) x0, (int) y0);
    }
  }

  public void flush() {}

  public void close() {
    synchronized(this.lock) {
      if (page != null) page.dispose();
    }
  }

  public void setFontStyle(int style) {
    synchronized(this.lock) {
      Font current = font;
      try {
        font = new Font("Monospaced", Font.PLAIN, fontsize);
      }
      catch (Exception e) {font = current;}
      if (page != null) page.setFont(font);
    }
  }

  public void setHeader(String header) {
    headermetrics = headerfont.getLineMetrics(header, 0, header.length(),
new FontRenderContext(null,false,false));
  }

  public void setHeaderFontStyle(int style) {
    synchronized(this.lock) {
      Font current = font;
      try {
        headerfont = new Font("SansSerif", Font.ITALIC, fontsize);
      }
      catch (Exception e) {font = current;}
      if (page != null) page.setFont(font);
    }
  }


  public void pageBreak() { synchronized(this.lock) { newpage(); } }

  public int getLinesPerPage() {return this.linesperpage; }

  protected void newline() {
    charnum = 0;
    linenum++;
    if (linenum >= linesperpage) {
      book.setPage(pagenum, this, pageFormat);
      page = null;
    }
  }

  public int print(Graphics g, PageFormat pf, int pageIndex) {
    g = (Graphics) book.getPrintable(pageIndex);
    return Printable.PAGE_EXISTS;
  }

  protected void newpage() {
    page = (Graphics2D) pj.getGraphics();
    book.append(this, pageFormat);
    linenum = 0;
    charnum = 0;
    pagenum++;
    page.setFont(headerfont);
    page.drawString(job.getJobName(), (int) pageFormat.getImageableX(),
(int) pageFormat.getImageableY());

    String s = "- "+pagenum+" -";
    FontRenderContext frc = new FontRenderContext(null, false, false);
    int w = (int) font.getStringBounds(s, frc).getWidth();
    page.drawString(s, (int) (x0 + (pageFormat.getImageableWidth() - w)/2),
(int) headery);
    w = (int) headerfont.getStringBounds(time, frc).getWidth();
    page.drawString(time, (int) (x0+pageFormat.getImageableWidth() - w),
(int) headery);

    int y = (int) (headery + headermetrics.getDescent() + 1);
    page.drawLine((int) x0, (int) y, (int)
(x0+pageFormat.getImageableWidth()), (int) y);

    page.setFont(font);
  }

  public static void main(String[] args) {
    String s = "This is a test";
    Font font = new Font("Monospaced", Font.PLAIN, 12);
    FontRenderContext frc = new FontRenderContext(null,false,false);
    LineMetrics lm = font.getLineMetrics(s,0,s.length(), frc);
    System.out.println(lm.getNumChars());
    Rectangle2D bounds = font.getStringBounds(s, frc);
    System.out.println(bounds.getWidth());
    JFrame testFrame = new JFrame();
    JTextArea testArea = new JTextArea();
    testFrame.getContentPane().add(testArea);
    testFrame.setVisible(true);
    Vector text = new Vector();
    text.addElement("This is the first line");
    text.addElement("This is the second line");
    text.addElement(".");
    text.addElement(".");
    text.addElement(".");
    text.addElement(".");
    text.addElement(".");
    text.addElement(".");
    int fontsize = 12;
    PrintableBook pb = new PrintableBook(testFrame, font, text, new
PageFormat());
  }
}

I think this will work if I get those two areas figured out.  I realize it
won't be very fast as there is already a bug report produced in the bug
parade identifying that printing is very, very slow and producing very large
spools, but some slow print is better than no print...

Thanks for any assistance you can provide and if you're having similar
printing woes, let's see if we can work together to figure this out.

If anyone from Sun is listening out there - how about a better overview of
how your new stuff is supposed to interact?  The documentation for the
individual classes is much improved, but I see nothing to give the big
picture.  Some small examples for major things like printing would be nice
too...

Thanks for any help or insight you provide and, if you have none to give,
thanks for reading this far down anyway.

Ross Dukeshier
Technical Details
Message-ID: <75ha4e$41d21@forums.borland.com>
Path: arc1-ca.pugleaf.net!unknown!not-for-mail

Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit
X-Google-Thread: f74b3,943c17f4d03b2f46,start
X-Google-Attributes: gidf74b3,public
From: "Ross Dukeshier" <dukeman@flash.net>
Subject: sample print class w/questions...
Date: 1998/12/19
Message-ID: <75ha4e$41d21@forums.borland.com>
X-Deja-AN: 424052121
Organization: Another Netscape Collabra Server User
X-MimeOLE: Produced By Microsoft MimeOLE V4.72.3110.3
Newsgroups: borland.public.jbuilder.java.language