Search code examples
javahtmlswingjlabeljoptionpane

Swing Dialogbox html formatting 'cutting off' half of the content


I have a dialog which I wish make a specific part bold. I know I have to do this with html however I seem to be losing half of the dialog message when I do this.

Original (No bold):

public class View extends JFrame {
    private final static String NEW_LINE = System
            .getProperty("line.separator");
    public void someMethodDisplayDialog(String string1, String string2, String string3) {
        JOptionPane.showMessageDialog(this,
                "An problem occured: " + string1
                        + NEW_LINE 
                        + string2 + " Error: "
                        + string3,
                "Error",
                JOptionPane.ERROR_MESSAGE);
    }
}

Lets say:

  • string1 = "Wrong Key!",
  • string2 = "Input",
  • string = "Z key pressed".

In the dialog box this displays:


A problem occurred: Wrong Key!
Input Error: Z key pressed
I want to bold the "Input Error:" section. I have this code:

        JOptionPane.showMessageDialog(this,
                "An problem occured: " + string1
                        + NEW_LINE + "<html><b>" 
                        + string2 + " Error:</b></html> "
                        + string3,
                "Error",
                JOptionPane.ERROR_MESSAGE);

When run, this bolds what I want, but 'cuts off' off the rest, eg. string3 is not displayed.
I have tried putting the closing </b></html> tags after string3.
Everything is displayed, but string3 is also bold, which I do not want!

I am I missing something blatantly obvious here? I am not sure why this is happening?


Solution

  • As it already told by @Andrew Thompson your message must be started with <html> tag. So your code should look like:

            JOptionPane.showMessageDialog(this,
                "<html>An problem occured: " + string1
                        + "<br><b>" 
                        + string2 + " Error:</b> "
                        + string3 + "</html>",
                "Error",
                JOptionPane.ERROR_MESSAGE);