处理自动创建的退出按钮?

Handling exit button which is create automatically?

我正在构建一个文本编辑器,但我不知道如何处理自动创建的 Swing 退出按钮上的侦听器。 我想在用户不保存文件时使用对话框,例如按退出按钮。

逐步进行:

  1. 声明一个布尔变量 saved 并将其默认值设置为 false。
  2. 当用户保存文件时,将其更改为 true
  3. 按下退出按钮时,检查变量。
  4. 如果true,退出,否则,提示用户保存文件。

所以,最后这个代码片段看起来像:

public boolean saved = false;

saveButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        saved = true;
        //Code to save file
    }
});

exitButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        if(saved)
            System.exit(0);
        else {
            //Code to prompt user to save file
        }
    }
});

假设您有 window 的句柄,假设它是一个 Window 对象(例如 JFrame 或其他类型的 window),您可以收听WindowEvent 个事件。这里以windowClosed为例,之前需要截取的可以换成windowClosing

    frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosed(WindowEvent e) {
            // do something here
        }
    });
final JFrame f = new JFrame("Good Location & Size");
// make sure the exit operation is correct.
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); 
f.addWindowListener( new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
        // pop the dialog here, and if the user agrees..
        System.exit(0);
    }
});

如此 answer to Best practice for setting JFrame locations 所示,它在退出前序列化帧位置和大小。