0

我在字符串中保存了更长的文本。我想在单个页面上打印两列中的文本。如何使用 Java Swing 做到这一点?

我不明白在需要使用新行时如何换行。我已经阅读了 Java 教程中的课程:打印FontMetrics,但除了.

Java API 中有什么好的方法,或者我可以使用什么好的库?

4

2 回答 2

1

您可能会使用 java.awt.print.PrinterJob 类来设置打印机作业,并使用 java.awt.font.TextLayout() 方法在打印机上渲染图形。

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.

于 2010-05-18T16:45:53.920 回答
0

有趣的问题,可能有一些复杂的方法使用 Document 接口;但基本上创建两个并排的 JTextPanes()。您可能会花费大量时间尝试自动测量文本,使其一分为二,但我会尝试在中间找到一个段落边界,大致平衡非空白字符的数量。如果文本已经结构化,您可以查看文档

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;
}

然后将您的文本添加到窗格中,如下所示:

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);

此外,您可能会在 HTMLEditorKit 中找到一些运气,尽管我不知道 HTML 是否提供了那种文本分割。

column1.setEditorKit(new HTMLEditorKit());
于 2010-05-17T15:10:08.977 回答