0

My question: How can i put the text e.printStackTrace prints into a JOptionPane window

My code is currently as follows:
excuse the shitty formatting :P

try {
  //SOME CODE
} catch (Exception e) {
  e.printStackTrace();
  JOptionPane.showMessageDialog(null,
     "An unexpected error has occurred:\n" + e.getMessage() + '\n' + Thread.currentThread().getStackTrace() +  "\nPlease send this error to ." + email + "\nThanks for your help.",
     "Error", JOptionPane.ERROR_MESSAGE);
}

this both prints the stack trace in the command line interface(i am using terminal) and it creates a JOptionPane but NOT with the same info as e.printStackTrace(). when running my program from a jar file, the command line interface won't be visible so the user will only get the JOptionPane window which doesnt have all of the info i need to succesfully identify the problem

Thanks in advance :)

herteladrian
  • 189
  • 1
  • 3
  • 15
  • Not sure a basic JOptionPane is your best bet, cause it's tricky for the user to copy and paste the stack trace, e.g. to email you with the issue. You want a JTextArea or similar. – user949300 Jan 20 '13 at 02:55
  • 1
    replace `Thread.currentThread().getStackTrace()` with `e.getStackTrace()` for one thing. – Jakob Weisblat Jan 20 '13 at 02:56

1 Answers1

6

Here, This is just some general code I came up with that will get you the same output as e.printStackTrace().

try {
    // some code
} catch (Exception e) {
    StringBuilder sb = new StringBuilder(e.toString());
    for (StackTraceElement ste : e.getStackTrace()) {
        sb.append("\n\tat ");
        sb.append(ste);
    }
    String trace = sb.toString();
    // Now, trace contains the stack trace
    // (However, you can only use it inside the catch block)
}

However, as was previously mentioned, you probably want a window in which you can scroll, as I don't think it'd fit very well in a JOptionPane.

MrCodeBlok
  • 146
  • 1
  • 3
  • 3
    *"I don't think it'd fit very well in a `JOptionPane`."* A `JOptionPane` can be made quite big if need be. It will use the preferred size of the content as a hint. Use the `JTextArea(rows,columns)` constructor to suggest a size. Of course, wrap it in a `JScrollPane`. See also [this answer](http://stackoverflow.com/questions/14011492/text-wrap-in-joptionpane/14011536#14011536). – Andrew Thompson Jan 20 '13 at 03:43