views:

90

answers:

2

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?

A: 

Interesting problem, there might be some sophiticated method using the Document interface; but basically create two side by side JTextPanes(). You could spend a lot of time trying to auto measure the text so it split in two, but I would just try to find a paragraph boundary in the middle which roughly balances the number of non-whitespace characters. If the text is already structured you can look at the Document

int findSplitBoundary(String x) {
 int midPoint = x.length()/2;
 for (int i = 0; i < Math.min(x.length()/2 - 2, 100); i++) {
  if (x.startsWith(".\n", midPoint - i)) return midPoint- i;
  if (x.startsWith(".\n", midPoint + i)) return midPoint- i;
 }
 return midPoint;
}

Then add your text to the panes as such:

JTextPane column1 = new JTextPane();
JTextPane column2 = new JTextPane();
split=findSplitBoundary(longText);
column1.setText(longText.substring(0, split));
column2.setText(longText.substring(split));
add(column1, BorderLayout.WEST);
add(column2, BorderLayout.EAST);

Also you might find some luck looking at the HTMLEditorKit, though I don't know if HTML offers the kind of text splitting.

column1.setEditorKit(new HTMLEditorKit());
Justin
+1  A: 

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.

Gilbert Le Blanc
Added a wrapping explanation to my answer.
Gilbert Le Blanc
@Gilbert: Thanks, your link was helpful.
Jonas