Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/374.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 退出时如何调用方法?_Java_Swing - Fatal编程技术网

Java 退出时如何调用方法?

Java 退出时如何调用方法?,java,swing,Java,Swing,我有一个swing应用程序。只要应用程序运行,我就可以在类内操作。但是,当用户在关闭时退出时,我必须将数据保存在文件中,如何保存它。这是我当前的实现 public static void main (String args[]) throws NumberFormatException, IOException{ displayCalendar p; Saver save = new Saver(); p = new displ

我有一个swing应用程序。只要应用程序运行,我就可以在类内操作。但是,当用户在关闭时退出时,我必须将数据保存在文件中,如何保存它。这是我当前的实现

    public static void main (String args[]) throws NumberFormatException, IOException{
        displayCalendar p;
        Saver save = new Saver();      
        p = new displayCalendar(save);

        JFrame fr = new JFrame();
        fr.add(p);
        fr.setDefaultCloseOperation(EXIT_ON_CLOSE);
        fr.setSize(500,500);
        fr.setVisible(true);
        save.saveAll();
}

这就是我试图在退出main之前保存的内容。但我根本无法实现那个功能。如何保存它?

使用
JFrame
添加
WindowListener

fr.addWindowListener(new WindowAdapter() {
   @Override
   public void windowClosing(WindowEvent e) {
       //Call the method here.
   }
}

这可能是你的解决办法

addWindowListener(new WindowAdapter()
        {
            @Override
            public void windowClosing(WindowEvent windowEvent)
            {
               // here your logic to save the data
                System.out.println("Window is being Closed");
                windowEvent.getWindow().dispose();
            }
        });

使用WindowAdapter在setDefaultCloseOperation上创建自定义操作:

看,我希望这对你有帮助。

看一看