Sam*_*num 3 java swing jtextpane
我正在使用JTextPane来编辑HTML.当我在GUI组件中输入换行符并在JTextPane上调用getText()时,我得到一个带换行符的字符串.如果我然后创建一个新的JTextPane并传入相同的文本,则忽略换行符.
为什么在输入换行符时JTextPane不插入<br>标签?这有一个很好的解决方法吗?
JTextPane test = new JTextPane();
test.setPreferredSize(new Dimension(300, 300));
test.setContentType("text/html");
test.setText("Try entering some newline characters.");
JOptionPane.showMessageDialog(null, test);
String testText = test.getText();
System.out.println("Got text: " + testText);
// try again
test.setText(testText);
JOptionPane.showMessageDialog(null, test);
testText = test.getText();
System.out.println("Got text: " + testText);
Run Code Online (Sandbox Code Playgroud)
样本输出:
<html>
<head>
</head>
<body>
Try entering some newline characters.
What gives?
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我意识到我可以在调用setText之前将换行符转换为HTML换行符,但这也会在HTML和BODY标记之后转换换行符,并且看起来很愚蠢.
我已经解决了这个问题,问题是我在setText中传入的纯文本.如果我取消调用setText,结果JTextPane.getText()是格式良好的HTML,正确编码了换行符.
我相信当我打电话时JTextPane.setText("Try entering some newline characters")它设置HTMLDocument.documentProperties.__EndOfLine__为"\n".此文档属性常量在此处定义.
解决方案是确保在将文本<p>传递给JTextPane.setText()方法时将文本包装在标记中(注意,style属性用于任何后续段落):
textPane1.setText("<p style=\"margin-top: 0\">Try entering some newline characters</p>");
Run Code Online (Sandbox Code Playgroud)
或者,在传入纯文本后,替换EndOfLineStringProperty(这更像是一个hack,我不推荐它):
textPane1.getDocument().putProperty(DefaultEditorKit.EndOfLineStringProperty, "<br/>\n")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7776 次 |
| 最近记录: |