I'm using a JEditorPane
to display some text. The problem is that I can't add multiple lines.
My code right now
public class Window extends JFrame {
private JEditorPane text = new JEditorPane();
public Window() {
setLayout(new BorderLayout());
setTitle("test");
setSize(500, 350);
setResizable(false);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
text.setEditable(false);
text.setContentType("text/html");
text.setText("<b>Some bold text</b><br>");
text.setText(text.getText() + "<br>Some text that is not bold but here <b>it is</b>");
getContentPane().add(text, BorderLayout.CENTER);
setVisible(true);
}
}
When it is in the same line ther is no problem, <br>
create a new line. But if it is in multiple statements, I can't get it to work.
It need to be in multiple statements because every statement is going to be a if
condition later on.
How can i make it do multiple lines?
The problem is that the JEditorPane wraps the text in <html><body> ... </body></html>
elements. For instance, when executing the following:
text.setText("<b>Some bold text</b><br>");
System.out.println("text content:\n" + text.getText());
You get this output:
text content:
<html>
<head>
</head>
<body>
<b>Some bold text</b><br>
</body>
</html>
Thus you need to either store the previous text before it is wrapped, or insert the addtional content before the </body>
For instance, in a very simple implementation, you could add the following attribute and method to your class:
private StringBuilder sb = new StringBuilder();
public String appendText(String text) {
return sb.append(text).toString();
}
Then, you could change your previous statements to set the text into:
...
text.setText(appendText("<b>Some bold text</b><br>"));
text.setText(appendText("<br>Some text that is not bold but here <b>it is</b>"));
...
which results in the desired behavior: