简体   繁体   中英

Using HTML tags in JOptionsPane

My question today is simple. I am attempting to use HTML tags in my Java code, specifically in a JOptionsPane. I have had almost everything so far work perfectly. I know I could probably accomplish the same thing using CSS but for now I am just trying to do it with tags if possible. Here is the specific line of code giving me trouble:

"<br><body bgcolor=black><table border=1><font size=4 color=white>batch<font size=6 color=white>1</font> of <font size=6 color=white>"+ofFiveDisplay+"</font></table></body>"

What the end result should be is the text Batch 1 of 2 . (The two is pulled from a variable) displayed on a single line in the text of the JOptionsPane . I want the "1" and "2" to be larger. I also want all of the text to be in white and the background of the text to be black.

I am able to add the black background and get the "1" or "2" white, but I cannot seem to change the "batch" text. Please let me know why I can not seem to change the "batch" text using the above code and what I can do to fix it. Thanks in advance!

Font is a deprecated tag and is not widely adopted so it might not work. Could you try by inlining CSS in a span like this:

"<span style='font-size:6; color:white'>"+ofFiveDisplay+"</span>

1st of all, whenever you need help post an MCVE so we can copy-paste it and be able to help you faster and better.

You were using font tag which on HTML5 is deprecated

To get to use font sizes, etc, the best way is using CSS inside your <html> tags as follows:

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class ShowMessageDialogExample {
    public static void main(String[] args) {
        JFrame frame = new JFrame("JOptionPane showMessageDialog example");
        String css = "<span style='font-size: 10; color: white; background-color: black'>";
        String batchCss = "<span style='font-size: 20;'>";
        String endSpanCss = "</span>";
        JOptionPane.showMessageDialog(frame, "<html>" + css + batchCss + " 1 " + endSpanCss + "of" + batchCss + " 2 " + endSpanCss + endSpanCss + "</html>");
        System.exit(0);
    }
}

I put the CSS part inside a variable so you don't have to repeat the code each time. Hope it helps and you follow the link I left above and apply this recommendation on your next questions and answers, so they are better and more valuable.

And here's the output:

在此输入图像描述


EDIT

After OP's comment

When I looked at the CSS guides they were a bit confusing

Here's a " guide " which describes how to use HTML5 , CSS and even javascript on a Java swing application. And another reference to the same topic.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM