[英]How to get JEditorPane to display text as in JTextArea?
I want to make JEditorPane
display the text as it is in the JTextArea
. 我想让
JEditorPane
像在JTextArea
一样显示文本。 The reason for using JEditorPane
is that I want to create links on specific text patterns (with a href
). 使用
JEditorPane
的原因是我想在特定的文本模式(带有a href
)上创建链接。 I have looked into JTextPane
but did not find an easy way of doing it. 我研究了
JTextPane
但没有找到简单的方法。 The text is left padded, so the padding and the preserving the correct number of spaces is important. 文本将被填充,因此填充和保留正确的空格数很重要。 The difference between the display is shown below:
显示之间的差异如下所示:
I want the JEditorPane
to display the text exact same way as in JTextArea
(on the left side). 我希望
JEditorPane
以与JTextArea
(在左侧)完全相同的方式显示文本。 Maybe, there is another and better of way of doing it? 也许,还有另一种更好的方法呢? Some text like
1233
will have links and associated event listeners will be triggered once I get the text display right. 当我正确显示文本时,某些文本(如
1233
将具有链接,并且关联的事件侦听器将被触发。
The code: 编码:
import javax.swing.*;
import javax.swing.text.JTextComponent;
import java.awt.*;
public class Test {
public static void main(String[] args)throws Exception {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
createAndShowGUI();
}
});
}
final static String sampleText=
"\n" +
" 1233 2001/16/07 This is test\n" +
" With padding\n" +
" more padding\n" +
" and more padding";
private static void createAndShowGUI() {
final JFrame frame = new JFrame("test");
//final JTextComponent textComponent=new JTextArea();
final JEditorPane textComponent=new JEditorPane();
textComponent.setContentType("text/html");
textComponent.setFont(textComponent.getFont().deriveFont(11.5f));// larger font
textComponent.setText(sampleText);
frame.getContentPane().add(textComponent);
frame.setPreferredSize(new Dimension(370,120));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
}
This can be a solution when using plain text: 使用纯文本时,这可以是一个解决方案:
textComponent.setFont(new JTextArea().getFont().deriveFont(11.5f));
but formatting is lost. 但格式丢失。 So, this does not work when I set the contentType to "text/html".
因此,当我将contentType设置为“ text / html”时,这不起作用。 The
JEditorPane
when I set the contenttype (even with Monospaced
font): 当我设置内容类型(甚至使用
Monospaced
字体)时,将使用JEditorPane
:
Solution is, no matter what textComponent
is (whether JTextArea
or JEditorPane
): 解决方案是,无论是什么
textComponent
( JTextArea
或JEditorPane
):
textComponent.setFont(new JTextArea().getFont().deriveFont(11.5f));
This forces JEditorPane
to use the same font as JTextArea
. 这将强制
JEditorPane
使用与JTextArea
相同的字体。 Additionally, replace spaces with html entities and newlines with <br>
: 此外,将空格替换为html实体,将换行符替换为
<br>
:
sampleText=sampleText.replaceAll("\n","<br>").replaceAll("\\s"," ");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.