Text wrap in JOptionPane?

14,480

Solution 1

A JOptionPane will use a JLabel to display text by default. A label will format HTML. Set the maximum width in CSS.

JOptionPane.showMessageDialog(
    this, 
    "<html><body><p style='width: 200px;'>"+exp.getMessage()+"</p></body></html>", 
    "Error", 
    JOptionPane.ERROR_MESSAGE);

More generally, see How to Use HTML in Swing Components, as well as this simple example of using HTML in JLabel.

Solution 2

Add your message to a text component that can wrap, such as JEditorPane, then specify the editor pane as the message to your JOptionPane. See How to Use Editor Panes and Text Panes and How to Make Dialogs for examples.

Addendum: As an alternative to wrapping, consider a line-oriented-approach in a scroll pane, as shown below.

error image

f.add(new JButton(new AbstractAction("Oh noes!") {
    @Override
    public void actionPerformed(ActionEvent action) {
        try {
            throw new UnsupportedOperationException("Not supported yet.");
        } catch (Exception e) {
            StringBuilder sb = new StringBuilder("Error: ");
            sb.append(e.getMessage());
            sb.append("\n");
            for (StackTraceElement ste : e.getStackTrace()) {
                sb.append(ste.toString());
                sb.append("\n");
            }
            JTextArea jta = new JTextArea(sb.toString());
            JScrollPane jsp = new JScrollPane(jta){
                @Override
                public Dimension getPreferredSize() {
                    return new Dimension(480, 320);
                }
            };
            JOptionPane.showMessageDialog(
                null, jsp, "Error", JOptionPane.ERROR_MESSAGE);
        }
    }
}));
Share:
14,480
laksys
Author by

laksys

Java (Spring, hibernate, REST) &amp; Javascript Developer.

Updated on June 08, 2022

Comments

  • laksys
    laksys almost 2 years

    I'm using following code to display error message in my swing application

    try {
        ...
    } catch (Exception exp) {
        JOptionPane.showMessageDialog(this, exp.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }
    

    The width of the error dialog goes lengthy depending on the message. Is there any way to wrap the error message?

  • trashgod
    trashgod over 11 years
    @laksys: Exactly, the String is automatically wrapped in a JLabel, which supports HTMl.
  • Yogu
    Yogu over 10 years
    Don't forget to html-escape the string, otherwise some special characters might not work.
  • Math
    Math over 10 years
    Exactly. E.g. using \n makes the code to not work, has to use <br /> instead.
  • Opal
    Opal about 10 years
    For the record, it is not necessary to close the tags, or even open the body. As long as there is the <html> tag then Java parses the HTML just fine.
  • pstanton
    pstanton almost 10 years
    @Lee why would you advise anyone to not close tags?
  • Opal
    Opal almost 10 years
    For the <html> tag it is not necessary to close it(others maybe). It's just quicker, easier and probably more readable.
  • gouessej
    gouessej about 9 years
    Use this to write less code to put the stack trace into a String: stackoverflow.com/a/4812589
  • WesternGun
    WesternGun over 6 years
    So, add <html> and </html> tag around the text and escape the text will suffice? Nice. But how can we make it an utility method, or any util jar just can do it well? This is a typical high frequency requirement.
  • Andrew Thompson
    Andrew Thompson over 6 years
    @FaithReaper The style (setting the width) is a vital part of making it working, not just wrapping it in HTML. You can confirm that by changing the simple example above to remove the style. "But how can we make it an utility method" IT's be pretty trivial to make a method that accepts a String (the text to be displayed) as well as an int (preferred width) then add the HTML/CSS around the (escaped) text using the int value for the width in an option pane. For more versatility, have the method return the 'HTML friendly' string instead of displaying it, then the programmer can ..
  • Andrew Thompson
    Andrew Thompson over 6 years
    .. decide how and where to display it. If that doesn't answer your query, then I apparently don't understand what you mean (which is quite possible).
  • WesternGun
    WesternGun over 6 years
    @AndrewThompson yes, I think setting the width is necessary. As for the utility method, I mean not only add the style, but to escape certain characters to display in HTML. I doubt there is no wheel invented.
  • Well Smith
    Well Smith about 6 years
    Your one is more appropriate where error messages are longer than expected.
  • Admin
    Admin over 2 years
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.