Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

For some weird 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 the output is:

Please fix <HTML><BODY BGCOLOR=#FFCCCC>this</BODY></HTML>
like image 520
jadrijan Avatar asked Jan 30 '12 18:01

jadrijan


4 Answers

The entire string needs to be enclosed within the HTML tags. For example:

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

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

like image 188
mre Avatar answered Oct 03 '22 16:10

mre


Also worth noting: it seems that having a newline in your string triggers JOptionPane to not render the string as HTML, whereas e.g. JLabel does allow newlines in the HTML.

like image 26
Robert Fleming Avatar answered Oct 03 '22 14:10

Robert Fleming


Enclose your entire string within html tags.

like image 27
RanRag Avatar answered Oct 03 '22 14:10

RanRag


The <HTML> and </HTML> tag specify that the input is in HTML. If you want to use HTML in Swing components, they have to either not be HTML, or be entirely in HTML. You can change the background of text by using the <FONT> tag, It might also be neater to enclose your text in <P> tags, but that's more a question of taste.

Try using

String msg = "<HTML><BODY><P>Please fix <FONT style="BACKGROUND-COLOR: #FFCCCC"> this</FONT></P></BODY></HTML>";
like image 30
DZittersteyn Avatar answered Oct 03 '22 14:10

DZittersteyn