Search code examples
javaswingprintingjava-2d

How can I print a text in two columns using Java Swing?


I have a longer text saved in a String. I would like to print the text in two columns on a single page. How can I do this using Java Swing?

I don't understand how I can wrap the text when it's time to use a new line. I have read Lesson: Printing in the Java tutorial, but I haven't found any useful methods for working with text or Strings except FontMetrics.

Is there any good methods in the Java API for this or is there any good library I can use for this?


Solution

  • You'll probably use the java.awt.print.PrinterJob class to set up the printer job, and render graphics on the printer using the java.awt.font.TextLayout() method.

    You'll have to divide up the java.awt.print.PageFormat that you get from the printer to divide the output into two columns.

    Here's a print example using the whole page.

    You have to manage String wrapping yourself. Look at the print() method in the print example. You'll see what Java classes you need to wrap text.