I want to make JEditorPane
display the text as it is in the JTextArea
. The reason for using JEditorPane
is that I want to create links on specific text patterns (with a href
). I have looked into JTextPane
but did not find an easy way of doing it. 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). 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.
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". The JEditorPane
when I set the contenttype (even with Monospaced
font):
Solution is, no matter what textComponent
is (whether JTextArea
or JEditorPane
):
textComponent.setFont(new JTextArea().getFont().deriveFont(11.5f));
This forces JEditorPane
to use the same font as JTextArea
. Additionally, replace spaces with html entities and newlines with <br>
:
sampleText=sampleText.replaceAll("\n","<br>").replaceAll("\\s"," ");