2

I'm building a Java Swing interface in which I have a HTML-styled jTextPane, which I use for displaying the current system status. I want to be able to display a few Strings (which may change over time), while using HTML to set the appearance and placement of the text. I use the line of code below to display two strings of them in the jTextPane.

jTextPane1.setText("<html><font size=\"4\" ><b><center> String A here! </center></b></font><br><br><font size=\"3\" ><center> String B here</center></font>");

What I want, is to insert two Strings (A and B) so that I can change them over time. But unfortunately, I cannot find the syntax to insert a String anywhere. Is there a simple way to do this? Thanks in advance.

4 Answers 4

4

Define your HTML code as template and use the placeholders %s for stringA and stringB. Then use String.format() to insert your strings. At the end set this in your TextPane.

String template = "<html><font size=\"4\" ><b><center>%s</center></b></font><br><br><font size=\"3\" ><center>%s</center></font>"
String text = String.format(template, stringA, stringB);
jTextPane1.setText(text);
Sign up to request clarification or add additional context in comments.

Comments

2
jTextPane1.getDocument().insertString(offset, stringToInsert, attributes);

Comments

2

You can use some constant strings like:

    final String PRE_HTML = "<html><font size=\"4\" ><b><center> ";
    final String MID_HTML = " </center></b></font><br><br><font size=\"3\" ><center> ";
    final String POST_HTML = "</center></font></html>";

And you can set like:

    String strA = "String A";
    String strB = "String B";
    jTextPane1.setText(PRE_HTML + strA + MID_HTML + strB + POST_HTML);

Comments

1

You could use String.format:

jTextPane1.setText(String.format("<html><font size=\"4\" ><b><center> %s </center></b></font><br><br><font size=\"3\" ><center> %s </center></font>", a, b));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.