使用 HTMLEditorkit 设置的 JTextPane 在与 一起使用时不支持文本对齐样式。标签
下面的代码片段运行时不会在 JTextPane 中显示任何文本。 预标记中的文本对齐样式根本不受尊重。如果删除文本对齐样式或将其设置为“左”,则文本将显示在 JTextPane 中。我们使用“pre”标签来维护空格和制表符缩进。
我的要求是:
1)应该能够以居中/右对齐方式查看文本。
2) 文本字符串中的空格和制表符需要按 JTextPane 上的原样显示。
任何帮助将不胜感激。!!
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
public class TestHTML {
public static void main(String[] args){
javax.swing.JTextPane editor = new javax.swing.JTextPane();
editor.setEditorKit(new javax.swing.text.html.HTMLEditorKit());
String htmlText = "<html><head></head><body>" +
"<pre style='text-align:center;color:blue;'> " +
"Hello Spaced World !!!</pre>" +
"</body></html>";
editor.setText(htmlText);
Document doc = editor.getDocument();
try {
System.out.println(doc.getText(0, doc.getLength()));
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
javax.swing.JFrame f = new javax.swing.JFrame("HTML Editor");
f.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(editor);
f.pack();
f.setVisible(true);
}
}
The code snippet below when run wont display any text in JTextPane.
The text-align style in pre tag not at all honoured. If text-align style is removed OR if it is set to 'left', the text is displayed in JTextPane. We are using 'pre' tag to maintain the white spaces and tab indentation.
My requirements are :
1) Should be able to see the text in center/right align fashion.
2) White spaces and tab in the text string need to displayed as it is on JTextPane.
Any help would be most appreciated.!!
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
public class TestHTML {
public static void main(String[] args){
javax.swing.JTextPane editor = new javax.swing.JTextPane();
editor.setEditorKit(new javax.swing.text.html.HTMLEditorKit());
String htmlText = "<html><head></head><body>" +
"<pre style='text-align:center;color:blue;'> " +
"Hello Spaced World !!!</pre>" +
"</body></html>";
editor.setText(htmlText);
Document doc = editor.getDocument();
try {
System.out.println(doc.getText(0, doc.getLength()));
} catch (BadLocationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
javax.swing.JFrame f = new javax.swing.JFrame("HTML Editor");
f.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(editor);
f.pack();
f.setVisible(true);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我怀疑
pre
元素最初是为了左对齐(对于从左到右的文本),这就是 Swing 忽略该请求的原因。为什么不尝试将其作为code
放入div
中呢?可见:我刚刚意识到单词之间的空格被压缩为 1。将每个单词替换为
& ;nbsp;
来解决这个问题。I suspect that the
pre
element was originally intended to be left aligned (for left to right text), and that is why Swing is ignoring the request. Why not try putting it ascode
inside adiv
instead? Vis:I just realized that the spaces between words were being compacted to 1. Replace each one with
to fix that.