LoginSignup
6
6

More than 5 years have passed since last update.

Swingで例外時にダイアログを出しスタックトレースを表示する

Last updated at Posted at 2013-04-23

Swingで例外が発生した際に、ダイアログを出してスタックトレースを表示します。

  • getStackTraceで取得したスタックトレースをStackTraceElementに格納して一行ずつ取り出します。
  • ダイアログの表示はJOptionPane.showMessageDialogを使います。第2引数にSwingのコンポーネントを指定できるので、取り出したスタックトレースをJTextAreaなどに書き出して表示させます。
AppDialog.java

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class AppDialog {

    public static void stackTraceDialog(Exception e) {
        // スタックトレースの書き出し
        String message = new String();
        StackTraceElement[] stackFrames = e.getStackTrace();
        for (int i = 0 ; i < stackFrames.length ; i++) {
            String stackFrame = stackFrames[i].toString();
            message = message + stackFrame + "\n";
        }

        // ダイアログウィンドウ用パネル
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        // ラベル
        JLabel label = new JLabel("処理できない例外が発生しました。");
        // テキストエリア
        JTextArea area = new JTextArea();
        area.setText(message);
        area.setCaretPosition(0); // テキストエリア内のテキストの表示位置の初期化
        area.setEditable(false); // 編集不能にする
        // テキストエリアにスクロール設置
        JScrollPane scrollpane = new JScrollPane(area);
        scrollpane.setPreferredSize(new Dimension(600, 200));
        // ダイアログにラベルとテキストエリアを貼る
        panel.add(label, BorderLayout.NORTH);
        panel.add(scrollpane, BorderLayout.SOUTH);

        // ダイアログ表示
        JOptionPane.showMessageDialog(null, panel, "Error", JOptionPane.ERROR_MESSAGE);
    }

例外が発生した際にcatchで上記AppDialog.stackTraceDialogを呼び出すと、次のようなウィンドウが表示されます。

stackTraceDialog

6
6
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6