0

每当用户关闭窗口时,我都想抛出异常,但我不确定这是否可能。这是我想做的一些代码:

import java.awt.event.*;
import javax.swing.*;


public class ExceptionTest extends JFrame{

    public static void main(String[] args) {
        try {
            new ExceptionTest();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public ExceptionTest() throws Exception{
        super("Exception Test");
        setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                super.windowClosed(e);
                //Throw Exception
            }
        });

        pack();
        setLocationRelativeTo(null);
        setVisible(true);
    }

}
4

3 回答 3

2

您可以RunTimeException按如下方式使用:

public ExceptionTest()  {
    super("Exception Test");
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosed(WindowEvent e)throws RuntimeException {
            throw new RuntimeException("WindowClosedException");
        }
    });
于 2013-05-16T16:27:31.583 回答
2

基本上你可以在那里抛出任何类型的 RuntimeExceptions。您可以在此处找到 RuntimeExceptions 列表:RuntimeException (Java Platform SE 6)

import java.awt.event.*;
import javax.swing.*;


public class ExceptionTest extends JFrame{

    public static void main(String[] args) {
        try {
            new ExceptionTest();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public ExceptionTest() throws Exception{
    super("Exception Test");
    setDefaultCloseOperation(DISPOSE_ON_CLOSE);

    addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosed(WindowEvent e) {
            super.windowClosed(e);
            throw new IllegalArgumentException("User closed this window!");
        }
    });

    pack();
    setLocationRelativeTo(null);
    setVisible(true);
}

}

于 2013-05-16T16:30:13.363 回答
1

You can throw a RuntimeException

addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                super.windowClosed(e);
                throw new RuntimeException();
            }
         });
于 2013-05-16T16:27:18.867 回答