Catch exceptions in javax.swing application

前端 未结 3 398
醉酒成梦
醉酒成梦 2021-01-12 19:41

I\'m working with javax.swing to make an aplication which generates forms from XML Schema (using JAXFront library) and stores the data filled by the user them i

相关标签:
3条回答
  • 2021-01-12 19:47

    Simplest version is to set the default uncaught exception handler:

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            // do something
        }
    });
    

    But that catches uncaught exceptions thrown in other parts of the program aswell.

    You could however catch only runtime exceptions thrown off the swing event dispatching thread using a proxy (See this page for more information, copied code from there):

    class EventQueueProxy extends EventQueue {
    
        protected void dispatchEvent(AWTEvent newEvent) {
            try {
                super.dispatchEvent(newEvent);
            } catch (Throwable t) {
                // do something more useful than: t.printStackTrace();
            }
        }
    }
    

    Now installing it like this:

    Toolkit.getDefaultToolkit().getSystemEventQueue().push(new EventQueueProxy());
    
    0 讨论(0)
  • 2021-01-12 19:54

    After you have called visualize() the only thread running is the Swing/AWT event dispatch thread. If you want to catch any exceptions you will need to do so in any of your listener methods that are called on this thread e.g.

    public void actionPerformed(ActionEvent e) {
      try {
        // Some code here
      } catch(RuntimeException e) {
        // Handling code here
      }
    }
    

    To prevent boilerplate you can have this code in a super class.

    Note that you can also set a default uncaught exception handler if you want to catch anything not already dealt with by the Swing/AWT thread.

    Note also that in general it is best practice to not catch subclasses of RuntimeException if you can avoid it.

    0 讨论(0)
  • 2021-01-12 20:04

    Try adding:

    setDefaultCloseOperation(EXIT_ON_CLOSE);
    

    to MyFrame constructor. Not sure though, but worth trying.

    0 讨论(0)
提交回复
热议问题