在一个 Swing 应用程序中,我需要预见一个字符串的文本换行,就像将它放入 MS Word 或 LibreOffice 等文字处理器程序时一样。提供相同的可显示区域宽度、相同的字体(字体和大小)和相同的字符串,如下所示:
- 可显示区域宽度:179 毫米(在 .doc 文件中,设置 A4 纵向页面 - 宽度 = 210 毫米,左边距 = 20 毫米,右边 = 11 毫米;段落格式为零边距)
- 字体 Times New Roman,14 号
- 测试字符串: Tadf fdas fdas daebjnbvx dasf opqwe dsa: dfa fdsa ewqnbcmv caqw vstrt vsip d asfd eacc
结果:
- 在 MS Word 和 LibreOffice 上,该测试字符串都显示在单行上,不会发生文本换行。
我的波纹管程序报告发生文本换行,2行
第 1 行: Tadf fdas fdas daebjnbvx dasf opqwe dsa: dfa fdsa ewqnbcmv caqw vstrt vsip d asfd
第 2 行:ecc
是否有可能实现和 MS Word in swing 一样的文字环绕效果?代码中可能有什么问题?
贝娄我的程序
public static List<String> wrapText(String text, float maxWidth,
Graphics2D g, Font displayFont) {
// Normalize the graphics context so that 1 point is exactly
// 1/72 inch and thus fonts will display at the correct sizes:
GraphicsConfiguration gc = g.getDeviceConfiguration();
g.transform(gc.getNormalizingTransform());
AttributedCharacterIterator paragraph = new AttributedString(text).getIterator();
Font backupFont = g.getFont();
g.setFont(displayFont);
LineBreakMeasurer lineMeasurer = new LineBreakMeasurer(
paragraph, BreakIterator.getWordInstance(), g.getFontRenderContext());
// Set position to the index of the first character in the paragraph.
lineMeasurer.setPosition(paragraph.getBeginIndex());
List<String> lines = new ArrayList<String>();
int beginIndex = 0;
// Get lines until the entire paragraph has been displayed.
while (lineMeasurer.getPosition() < paragraph.getEndIndex()) {
lineMeasurer.nextLayout(maxWidth);
lines.add(text.substring(beginIndex, lineMeasurer.getPosition()));
beginIndex = lineMeasurer.getPosition();
}
g.setFont(backupFont);
return lines;
}
public static void main(String[] args) throws Exception {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTextPane txtp = new JTextPane();
frame.add(txtp);
frame.setSize(200,200);
frame.setVisible(true);
Font displayFont = new Font("Times New Roman", Font.PLAIN, 14);
float textWith = (179 * 0.0393701f) // from Millimeter to Inch
* 72f; // From Inch to Pixel (User space)
List<String> lines = wrapText(
"Tadf fdas fdas daebjnbvx dasf opqwe dsa: dfa fdsa ewqnbcmv caqw vstrt vsip d asfd eacc",
textWith,
(Graphics2D) txtp.getGraphics(),
displayFont);
for (int i = 0; i < lines.size(); i++) {
System.out.print("Line " + (i + 1) + ": ");
System.out.println(lines.get(i));
}
frame.dispose();
}