2 * Svjatoslav Commons - shared library of common functionality. Author: Svjatoslav Agejenko.
3 * This project is released under Creative Commons Zero (CC0) license.
5 package eu.svjatoslav.commons.gui.dialog;
10 import static javax.swing.BoxLayout.Y_AXIS;
12 public class ExceptionDialog {
14 public ExceptionDialog(final Exception exception) {
15 showException(exception);
19 * This method is for testing
21 * @param args commandline arguments
23 public static void main(final String[] args) {
25 final Throwable cause = new Throwable("details.....");
27 final Exception exception = new Exception("test", cause);
29 new ExceptionDialog(exception);
33 * @param exception exception to show
35 public void showException(final Exception exception) {
36 final JPanel contentPanel = new JPanel(new BorderLayout());
37 contentPanel.add(getTopPanel(exception), BorderLayout.NORTH);
38 contentPanel.add(getStackTraceView(exception.getCause()), BorderLayout.CENTER);
40 final JFrame frame = new JFrame("Exception occurred!");
41 frame.getContentPane().add(contentPanel);
42 frame.setSize(800, 600);
43 frame.setVisible(true);
44 frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
45 frame.setLocationRelativeTo(null); // center frame on screen
48 private TextArea getStackTraceView(Throwable cause) {
49 final StringBuilder buffer = new StringBuilder();
52 // if cause is available, show original stack trace
53 buffer.append("Stack trace:\n");
54 final StackTraceElement[] stackTrace = cause.getStackTrace();
55 enlistStackTraceElements(buffer, stackTrace);
57 // otherwise show at least current stack trace
58 buffer.append("Stack trace from original cause is not available.\n" +
59 "Showing current stack trace instead:\n");
60 enlistStackTraceElements(buffer, new Exception("Stack trace").getStackTrace());
63 return new TextArea(buffer.toString());
66 private void enlistStackTraceElements(StringBuilder buffer, StackTraceElement[] stackTrace) {
67 for (final StackTraceElement stackTraceElement : stackTrace)
68 buffer.append(stackTraceElement.toString()).append("\n");
71 private JPanel getTopPanel(Exception exception) {
73 final JPanel topPanel = new JPanel();
74 topPanel.setLayout(new BoxLayout(topPanel, Y_AXIS));
78 new JLabel("Exception type: " + exception.getClass().getCanonicalName()));
81 topPanel.add(new JLabel("Error message: " + exception.getMessage()));
84 Throwable cause = exception.getCause();
85 if (cause != null && cause.getMessage() != null)
86 topPanel.add(new JLabel("Cause: " + cause.getMessage()));