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);
46 centerFrameOnScreen(frame);
49 private void centerFrameOnScreen(JFrame frame) {
50 final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
52 (screenSize.width - frame.getWidth()) / 2,
53 (screenSize.height - frame.getHeight()) / 2);
56 private TextArea getStackTraceView(Throwable cause) {
57 final StringBuilder buffer = new StringBuilder();
60 // if cause is available, show original stack trace
61 buffer.append("Stack trace:\n");
62 final StackTraceElement[] stackTrace = cause.getStackTrace();
63 enlistStackTraceElements(buffer, stackTrace);
65 // otherwise show at least current stack trace
66 buffer.append("Stack trace from original cause is not available.\n" +
67 "Showing current stack trace instead:\n");
68 enlistStackTraceElements(buffer, new Exception("Stack trace").getStackTrace());
71 return new TextArea(buffer.toString());
74 private void enlistStackTraceElements(StringBuilder buffer, StackTraceElement[] stackTrace) {
75 for (final StackTraceElement stackTraceElement : stackTrace)
76 buffer.append(stackTraceElement.toString()).append("\n");
79 private JPanel getTopPanel(Exception exception) {
81 final JPanel topPanel = new JPanel();
82 topPanel.setLayout(new BoxLayout(topPanel, Y_AXIS));
86 new JLabel("Exception type: " + exception.getClass().getCanonicalName()));
89 topPanel.add(new JLabel("Error message: " + exception.getMessage()));
92 Throwable cause = exception.getCause();
93 if (cause != null && cause.getMessage() != null)
94 topPanel.add(new JLabel("Cause: " + cause.getMessage()));