Finally a decent MessageBox!
Tuesday, December 8th, 2009by Josef from Eden Foundation.
There is one frustration every Swing programmer shares: The message box system. The class JOptionPane, that comes with the Java Runtime Environment, is indeed versatile – but at the same time agonizing because of a very basic problem. Long messages don’t wrap… (click on the image to see what I mean)
This is the default behavior. There are various workarounds, the best that I’ve read about being to override the getMaxCharactersPerLineCount() method through a subclass. It’s a decent solution.
But once you start thinking about a bad class, you start getting wishful. And my wishlist came to include:
- HTML-formatting for my messages (so some things can be written in bold or italic).
- Possibility for the user to select and copy parts of the message, or it’s entirety, for sending in chats or emails when communicating with support.
- Support for really, really long messages, the ones that are as long as License agreement! for the cases where this actually is desirable. If so, the message box should not disappear partly outside the screen. Instead, the message should be scrollable.
As I couldn’t find my dreambox anywhere on the net, I finally took the time to fix my own. I found it especially challenging because of the LayoutManagers that just didn’t seem to want to do what I want, but in the end, a tip from Stanislav Lapitsky helped me sort it out. He had a quick-and-dirty on how to figure out the height of a JEditorPane if you are locking it’s width:
http://java-sl.com/tip_text_height_measuring.html
So I’ve made a wrapper class that I call instead of JOptionPane, that wraps my message strings into a JEditorPane before displaying them. The key part of the code was to embed the text messages in a nice component.
-
}
-
-
-
int maxWidth = 400;
-
-
String htmlizedMessage = null;
-
if (message.contains("<p>") || message.contains("<P>")
-
|| message.contains("<br>") || message.contains("<BR>")
-
|| message.contains("<Br>"))
-
htmlizedMessage = message;
-
else
-
htmlizedMessage = message.replace("\n", "<BR>");
-
-
int h = getContentHeight(htmlizedMessage, maxWidth);
-
-
text.setBorder(null);
-
text.setBackground(null);
-
text.setEditable(false);
-
-
int titleHeight = 0;
-
if (shortTitle != null) {
-
lblTitle.setFont(lblTitle.getFont().deriveFont(
-
lblTitle.getFont().getSize() * 1.5f));
-
lblTitle.setMaximumSize(lblTitle.getPreferredSize());
-
titleHeight = lblTitle.getPreferredSize().height;
-
}
-
scroll.setBorder(null);
-
htmlizedMessage, maxWidth))));
-
-
return pnl;
-
}
The result looks like this:
…like this…
…or this…
…or if the message is really, really long and almost qualifies to be an End User License Agreement (as if any end users ever have the time and legal knowledge to understand those), like this:
You can find the full source here:



