gpt4 book ai didi

java - JFrame 在关闭时拦截退出以保存数据

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:55:26 26 4
gpt4 key购买 nike

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

最佳答案

您应该尝试注册一个 WindowAdapter并覆盖它的 windowClosing方法。有关详细信息,请参阅 How to Write Window Listeners .

关于java - JFrame 在关闭时拦截退出以保存数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7650990/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com