摆动丢失异常

Swing lost exception

当我启动模态对话框并且当它呈现异常时,该异常出现在某个地方。我可以在调用 dialog.setVisible() 的代码中捕获它吗?

P.S。我知道 Thread.setUncaughtExceptionHandler,我需要从调用该对话框的代码中捕获它。

P.P.S。提前致谢,安德烈/。

public class TestSwing {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    JDialog jDialog = new JDialog();
                    JTable table = new JTable();
                    table.setModel(new DefaultTableModel() {
                        @Override public int getColumnCount() {return 1;}
                        @Override public int getRowCount() {return 1;}
                        @Override
                        public Object getValueAt(int row, int column) {
                            throw new RuntimeException("Hello");
                        }
                    });

                    jDialog.add(table);
                    jDialog.setModal(true);
                    jDialog.pack();
                    jDialog.setVisible(true);

                    System.out.println("dialog closed");

                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("got it");
               }

           }
        });
    }
}

不,你不能,因为异常不在你的对话中,而是在线程中。 Dialog.setVisible() 等待对话框消失,但不要停止当前线程。但我有一个技巧可以帮助您获得所需的行为。

public class TestSwing {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    JDialog jDialog = new JDialog();
                    JTable table = new JTable();
                    table.setModel(new DefaultTableModel() {
                        @Override public int getColumnCount() {return 1;}
                        @Override public int getRowCount() {return 1;}
                        @Override
                        public Object getValueAt(int row, int column) {
                            throw new RuntimeException("Hello");
                        }
                    });

                    jDialog.add(table);
                    jDialog.setModal(true);
                    jDialog.pack();
                    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {

                        @Override
                        public void uncaughtException(Thread t, Throwable e) {
                            jDialog.setVisible(false);
                            Thread.setDefaultUncaughtExceptionHandler(null);
                            throw new RuntimeException(e);
                        }
                    });
                    jDialog.setVisible(true);

                    System.out.println("dialog closed");

                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("got it");
               }

           }
        });
    }
}