【问题标题】:JFrame intercept exit on close to save dataJFrame拦截退出关闭以保存数据
【发布时间】:2011-10-04 16:20:21
【问题描述】:

我创建了一个窗口,想用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());
        }
    }       
}

}

【问题讨论】:

    标签: java swing save jframe exit


    【解决方案1】:

    您应该尝试注册WindowAdapter 并覆盖其windowClosing 方法。如需更多信息,请参阅How to Write Window Listeners

    【讨论】:

      猜你喜欢
      • 2011-12-09
      • 2011-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 2013-08-07
      相关资源
      最近更新 更多