将事件添加到动作侦听器而不删除默认动作?

时间:2013-03-13 17:03:18

标签: java

我想这样做,以便当我关闭我的GUI时,它将在我的主类中运行一个方法,但之后也会关闭?

请帮助谢谢

3 个答案:

答案 0 :(得分:1)

假设你正在使用Java Swing:

    JFrame frame = new JFrame();
    frame.setTitle("Project Planner");
    frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent event) {
            exitProcedure();
        }
    });

public void exitProcedure() {
    frame.dispose();
    System.exit(0);
}

只需在dispose方法之前添加您想要执行的操作。

答案 1 :(得分:0)

在GUI的WindowAdapter方法中尝试addWindowListener()的实现。

答案 2 :(得分:0)

为此,您需要将WindowListener注册到关联的JFrame。并覆盖windowClosing()方法。

编辑
为了从String数组中随机选择一个字符串,您可以使用java.util.Random API。例如,此处是String的数组,每次都是JFrame已关闭,String从此数组中随机挑出,并以方法callMeBeforeExit打印。

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import java.awt.event.WindowEvent;
import java.awt.event.WindowAdapter;
import java.awt.BorderLayout;
import java.util.Random;
class WorkBeforeClose extends  JFrame
{
    String[] strings = {
                            "Hello",
                            "World",
                            "Java",
                            "OOPs"
                        };
    public void showGUI()
    {
        setTitle("Close me");
        getContentPane().add(new JLabel("Close me"),BorderLayout.NORTH);
        addWindowListener(new WindowAdapter()
        {
            @Override
            public void windowClosing(WindowEvent evt)
            {
                callMeBeforeExit();
                System.exit(0);//Don't write this line if you don't want your program to exit
            }
        });
        setSize(200,200);
        setVisible(true);
    }
    private void callMeBeforeExit()
    {
        Random random = new Random();
        int i = random.nextInt(strings.length - 1);//Defines the Range of numbers to be chosen randomly.
        System.out.println(strings[i]);
    }
    public static void main(String st[])
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                WorkBeforeClose wbc = new WorkBeforeClose();
                wbc.showGUI();
            }
        });
    }
}