Home > Software engineering >  How to write stack exception in JLabel of Swing?
How to write stack exception in JLabel of Swing?

Time:01-04

I have to write stack exceptions in a label and a log file:

try {
   ...
} catch(Exception e) {
    File file = new File(pathFile   "//error.log");
    PrintStream ps = new PrintStream(file);
    e.printStackTrace(ps);
    ps.close();
}

How to write e in a Swing JLabel too?

CodePudding user response:

I use a JOptionPane

catch (Exception e) {
    java.io.StringWriter sw = new java.io.StringWriter();
    java.io.PrintWriter pw = new java.io.PrintWriter(sw);
    e.printStackTrace(pw);
    String stackTrace = sw.toString();
    javax.swing.JTextArea textArea = new javax.swing.JTextArea(stackTrace);
    javax.swing.JScrollPane scrollPane = new javax.swing.JScrollPane(textArea);
    javax.swing.JOptionPane.showMessageDialog(null,
                                              scrollPane,
                                              e.toString(),
                                              javax.swing.JOptionPane.ERROR_MESSAGE);
}

Note that the first argument in the call to method showMessageDialog is null since the code in your question does not show any Swing components. You should try to use an actual component from your GUI rather than null.

The second argument to method showMessageDialog is an Object which basically means it can be anything you like. In the above code it is a scroll pane. JOptionPane knows how to handle and display it.

Method printStackTrace, in class java.lang.Throwable is overloaded. The above code demonstrates one way to get the entire stack trace as a single string. Refer to the javadoc for method printStackTrace and PrintWriter constructor and class StringWriter.

In fact, I have a utility class.

public class MessageWindow {
    public static void showError(Exception e) {
        java.io.StringWriter sw = new java.io.StringWriter();
        java.io.PrintWriter pw = new java.io.PrintWriter(sw);
        e.printStackTrace(pw);
        String stackTrace = sw.toString();
        javax.swing.JTextArea textArea = new javax.swing.JTextArea(stackTrace);
        javax.swing.JScrollPane scrollPane = new javax.swing.JScrollPane(textArea);
        javax.swing.JOptionPane.showMessageDialog(null,
                                                  scrollPane,
                                                  e.toString(),
                                                  javax.swing.JOptionPane.ERROR_MESSAGE);
    }
}

Then I just call the method from the catch block.

catch (Exception e) {
    MessageWindow.showError(e);
}
  •  Tags:  
  • Related