【问题标题】:Make JButton Close a Window But Run Code In WindowClosing(WindowsEvent e) Before Closing使 JButton 关闭一个窗口,但在关闭之前在 WindowClosing(WindowsEvent e) 中运行代码
【发布时间】:2012-03-20 05:20:19
【问题描述】:

当用户单击关闭按钮或另一个显示退出的 JButton 时,我必须将程序的状态保存在 xml 中。我有它,所以它在窗口关闭时使用 WindowListener 运行它运行它。但这仅在您单击红色 X 关闭按钮时才有效,但在您有另一个按钮时无效。我可以在 actionListener 中为按钮执行 System.exit(0) 之前运行它,但是我需要的一些类的信息我无法从那个地方访问。

这是给框架的。

frame.addWindowListener(new WindowListener(){
    public void windowActivated(WindowEvent arg0){}
    public void windowClosed(WindowEvent arg0){}
    public void windowClosing(WindowEvent arg0)
    {
        myScreen.write.writeToXmlFile(myScreen.pics, myScreen.row, myScreen.col);
    }
    public void windowDeactivated(WindowEvent arg0){}
    public void windowDeiconified(WindowEvent arg0){}
    public void windowIconified(WindowEvent arg0){}
    public void windowOpened(WindowEvent arg0){}
});

这是按钮中的代码。

public void actionPerformed(ActionEvent arg0) {
        System.exit(0);
}

我无法从包含按钮的类访问 myScreen。

【问题讨论】:

    标签: java swing jframe jbutton windowlistener


    【解决方案1】:
    I do not have access to myScreen from the class that has button in it.
    

    JButton#doClick(); 可以做到这一点

    但正确的方式也可能是(也许)

    • public void windowClosing(WindowEvent arg0)

    第一。无效或类

    • create screenshot

    2.nd 无效或类

    • setVisible(false) for Top-Level Container(s)

    第三类无效或类

    • save applications states

    第 4 个空位或类别

    • System.exit()

    当然你可以将所有 4 个空位(类)放在一个中,但在上午的情况下,代码只会更加清晰易读

    【讨论】:

    • 非常聪明的想法!我不知道您可以进行“虚拟”点击。我刚刚在课堂上制作了一个可以访问的虚拟按钮,当按下它时,我调用 doClick,然后在退出之前执行这些操作。纯粹的天才!
    • @Captain Gh0st 很高兴为您提供帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 1970-01-01
    • 2021-03-27
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    相关资源
    最近更新 更多