JOptionPane showMessageDialog - a Java class to show long messages

Some times when exceptions occur when users are running a Java JFC/Swing application, it's nice to be able to show them a long message about what happened, i.e., something more than a one-line message. To that end I created a really simple Error Message Panel (ErrorMessagePanel.java) that you can use with the JOptionPane to display long messages.

ErrorMessagePanel is a simple Java class that extends a JPanel that you can easily use with the JOptionPane showMessageDialog method. I'll quickly run you through the process of using my ErrorMessagePanel class.

First, here's what the error message panel looks like when it is used with the showMessageDialog method of the JOptionPane class:

A sample error message dialog using my ErrorMessagePanel.java class.

Next, here is the Java source code I used to create this JOptionPane dialog:

 JOptionPane.showMessageDialog(myJFrame, 
                               new ErrorMessagePanel("A SIMULATED error occurred trying to write to a backup file.\n"));

Next, here is the source code for my ErrorMessagePanel class:

package com.devdaily.swingutils;

import java.awt.*;
import javax.swing.*;

/** This is non-production code, be careful. */
public class ErrorMessagePanel extends JPanel
{
  BorderLayout borderLayout1 = new BorderLayout();
  JScrollPane messageScrollPane = new JScrollPane();
  JTextArea messageTextArea = new JTextArea();
  String message;

  public ErrorMessagePanel(String message)
  {
    this.message = message;
    try
    {
      jbInit();
    }
    catch(Exception ex)
    {
      ex.printStackTrace();
    }
  }

  private ErrorMessagePanel()
  {
  }

  void jbInit() throws Exception
  {
    this.setLayout(borderLayout1);
    messageTextArea.setEnabled(true);
    messageTextArea.setEditable(false);
    messageTextArea.setLineWrap(true);
    messageTextArea.setText(message);
    messageTextArea.setSize(messageTextArea.getPreferredSize());
    messageTextArea.setPreferredSize(messageTextArea.getPreferredSize());
    this.add(messageScrollPane, BorderLayout.CENTER);
    messageScrollPane.getViewport().add(messageTextArea, null);
  }
  public void setText(String text)
  {
    this.message = text;
  }
}

As you can guess from looking at the source code, I just created this class very quickly with JBuilder. (You can tell by the jbInit method.)

I created this class for my own trivial purposes, but I encourage you to do something like this within your own Java JFC/Swing GUI applications. Some times when things go bad, it's nice to give the user as much detail as possible about the error, and this approach makes it very easy to give the user a lengthy description of what happened. If you combine that with the built-in JOptionPane dialog methods (showMessageDialog, showInputDialog, etc.), you can create simple, friendly information, warning, and error messages.