Text wrap in JOptionPane?
Asked Answered
G

3

33

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?

Gaven answered 23/12, 2012 at 13:53 Comment(0)
C
59

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.

Carey answered 23/12, 2012 at 14:12 Comment(10)
@laksys: Exactly, the String is automatically wrapped in a JLabel, which supports HTMl.Pardon
Don't forget to html-escape the string, otherwise some special characters might not work.Miru
Exactly. E.g. using \n makes the code to not work, has to use <br /> instead.Edile
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.Tomkin
@Lee why would you advise anyone to not close tags?Goldin
For the <html> tag it is not necessary to close it(others maybe). It's just quicker, easier and probably more readable.Tomkin
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.Obolus
@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 ..Carey
.. 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).Carey
@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.Obolus
P
33

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);
        }
    }
}));
Pardon answered 23/12, 2012 at 13:57 Comment(2)
Use this to write less code to put the stack trace into a String: stackoverflow.com/a/4812589Movable
Your one is more appropriate where error messages are longer than expected.Carraway
W
0

catch (Exception e) { e.printStackTrace();

                StringBuilder sb = new StringBuilder(e.toString());
                for (StackTraceElement ste : e.getStackTrace()) {
                    sb.append("\n\tat ");
                    sb.append(ste);
                }
                  
                JTextArea jta = new JTextArea(sb.toString());
                JScrollPane jsp = new JScrollPane(jta) {
                    @Override
                    public Dimension getPreferredSize() {
                        return new Dimension(750, 320);
                    }
                };
                JOptionPane.showMessageDialog(
                        null, jsp, "Error", JOptionPane.ERROR_MESSAGE);
                break; /// to show just one time 
            }
Waves answered 1/12, 2021 at 1:20 Comment(1)
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.Sequester

© 2022 - 2024 — McMap. All rights reserved.