'Setting font size for a print operation from a text component

I have the following program that puts a text string in a JTextArea and offers a print dialog for printing it:

public class PrintTest
{
  private static String fontName = Font.MONOSPACED; // "Verdana"
  private static FontUIResource defaultFixedWidthCellFont = new FontUIResource(fontName, Font.PLAIN, 16);
  public static FontUIResource getDefaultCellFont() { return defaultFixedWidthCellFont; }

  public static void main(String[] args)
  {
    JFrame frame = new JFrame("Print test");
    JTextArea textArea = new JTextArea();
    
    textArea.setEditable(false);
    textArea.setFont(getDefaultCellFont());
    textArea.setPreferredSize(new Dimension(400,200));

    textArea.setText("one and two and three");
    JScrollPane scrollPane = new JScrollPane(textArea);
    frame.add(scrollPane);
    frame.pack();
    frame.setVisible(true);
    
    try { textArea.print(); }
    catch (PrinterException pe) { pe.printStackTrace(); }

  }

}

In the real application, the text area does not need to be edited, it does need to be a fixed width font of this size. I am willing to use a text component other than a JTextArea, as long as I can set it to a fixed width font size and put it in a JScrollPane. I do not want any text wrapping. After getting put on the screen, it does not change (it's a report).

The problem is that the text, when printed on the printer, is too large. I do not want to reduce the size of the text in the window. I do not want to put the text in a file and print the file. The text is one long string in my Java program, there's no need to make a file of it.

When I attempt to search solutions, I get lots of articles about printing from eclipse, using System.out.println, and an occasional article that involves using Graphics objects to render individual text strings. I was hoping for something simpler; the program does do the printing, I just need a different font.

I have tried putting the text into another JTextArea and giving it a derived font with a different size, but that didn't work -- I did not render that text area, and don't know if that would matter. Is that a way to get this done? I've seen references to off-screen buffers for graphics, but don't know how I'd go about telling my text component to render itself to an offscreen buffer.

Or is there a better way to get this done?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source