JFrame拦截退出,接近保存数据

trs*_*trs 3 java swing save exit jframe

我创建了一个窗口,并希望使用windowStateChanged方法拦截出口,以便在应用程序关闭之前保存数据.但是,它似乎没有在数据关闭之前保存数据.我怎么能纠正这个?

见下面的代码:

public class InventoryMainFrame extends JFrame implements WindowStateListener{
    //set up the main window - instantiate the application
  private InventoryInterface inventoryInterface;    //panel that contains menu choices and buttons

  public InventoryMainFrame(){   //main window        
      setTitle("Inventory System");
      setSize (500,500);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLayout(new BorderLayout());
      //setLocationRelativeTo(null);    //center window on the screen           
      inventoryInterface = new InventoryInterface();    //set up the panel that contains menu choices and buttons
      add(inventoryInterface.getMainPane());         //add that panel to this window                   
      pack();
      setVisible(true); 

      //display window on the screen           
  }

public static void main(String[] args) {        
    //sets up front end of inventory system , instantiate the application
    InventoryMainFrame aMainWindow = new InventoryMainFrame( );
}

@Override
public void windowStateChanged(WindowEvent w) {
    //intercept the window close event so that data can be saved to disk at this point
    if (w.getNewState()==WindowEvent.WINDOW_CLOSED){
        //save the index file
        try{
          inventoryInterface.getInventory().saveIndexToFile();
          System.out.println("saving");
          dispose();  //dispose the frame
         }
        catch(IOException io){
            JOptionPane.showMessageDialog(null,io.getMessage());
        }
    }       
}
Run Code Online (Sandbox Code Playgroud)

}

mre*_*mre 5

您应该尝试注册WindowAdapter并覆盖其windowClosing方法.有关更多信息,请参见如何编写窗口侦听器.