Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert java variable in html-styled jTextPane

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.

like image 726
Frank D. Avatar asked Mar 19 '26 21:03

Frank D.


1 Answers

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);
like image 52
Kai Avatar answered Mar 22 '26 11:03

Kai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!