čtvrtek 27. srpna 2009

Java Swing: Flexible Message Dialog

JOptionPane makes life of a developer much easier when one need to show simple message or input dialogs. However, when a huge String or a String with many line breaks is passed to it's showMessageDialog() method, then the message dialog may the screen. For the user, it's better, when the very large messages are wrapped in an JScrollPane. It is possible to pass JScrollPane as an message parameter into to JOptionPane, so far so good. Unfotunatelly, it's not possible to limit the maximum size of the dialog. Finally, I have finished with this solution:
JTextArea textArea = new JTextArea();
// better to keep it true, so the user is able to copy the message to the clipboard
textArea.setCaretPosition(0); // jump to the beginning
JScrollPane scrollPane = new JScrollPane(textArea);
scrollPane.setBorder(null); // no border, please
Dimension scrollPaneSize = scrollPane.getPreferredSize();
Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
scrollPaneSize.width = Math.min(scrollPaneSize.width, Math.max(screen.width / 2, 260));
scrollPaneSize.height = Math.min(scrollPaneSize.height, Math.max(screen.height / 2, 125));
JOptionPane jOptionPane = new JOptionPane(scrollPane, JOptionPane.ERROR_MESSAGE);
JDialog dialog = jOptionPane.createDialog(parent, "Error");
// it could be nice to let the user resize the dialog, but then the scrollPane always shows the scroll bar
The size of the scrollPane grows or shrinks. It's maximum is screen size divided by two, or (260, 125) points (just in case the screen is too small :-)). I have found out, that (260, 125) is roughly the size of the empty massage dialog.