When I try to use HTML with `JOptionPane`, HTML tags are printed instead of HTML formatting

For some strange reason, when I try to use HTML with JOptionPane, HTML tags are printed instead of HTML formatting.

String msg = "Please fix <HTML><BODY BGCOLOR=#FFCCCC>this</BODY></HTML>";
JLabel message = new JLabel(msg);
JOptionPane.showMessageDialog(MyApp.this, message, "Error!", JOptionPane.ERROR_MESSAGE);

and output:

Please fix <HTML><BODY BGCOLOR=#FFCCCC>this</BODY></HTML>
+5
source share
4 answers

The entire string must be enclosed in HTML tags. For instance:

button = new JButton("<html><b><u>T</u>wo</b><br>lines</html>");

For more information, see How to Use HTML in Swing Components .

+15
source

It is also worth noting: it seems that the presence of a string in a trigger string JOptionPanedoes not display the string as HTML, whereas, for example, it JLabelallows newline characters in HTML.

+9
source

html.

+5

The tag <HTML>also </HTML>indicates that the input file is in HTML. If you want to use HTML in Swing components, they must either not be HTML, or be completely in HTML. You can change the background of the text using a tag <FONT>, it can also be neatly wrapped your text in tags <P>, but this is still a question of taste.

Try using

String msg = "<HTML><BODY><P>Please fix <FONT style="BACKGROUND-COLOR: #FFCCCC"> this</FONT></P></BODY></HTML>";
+4
source

All Articles