【问题标题】:How can I update JFrame objects during WindowClosing event?如何在 WindowClosing 事件期间更新 JFrame 对象?
【发布时间】:2017-12-22 23:47:01
【问题描述】:

我有一些关闭步骤需要在 WindowClosing 事件期间执行,然后才能被释放。一切都正确执行,但我想添加在关闭 JFrame 中的现有 JLabel 中提供关闭状态消息的功能。是否可以在 WindowClosing 事件期间更新 JLabel 文本?

【问题讨论】:

  • 参见this answer,了解如何影响JFrame 的关闭行为。
  • 我看不到在 Windowclosing 事件中该答案解决了对 JFrame 组件进行更新的位置。

标签: java swing jframe


【解决方案1】:

当然。只需确保在开始与组件交互之前未释放组件即可。

SwingUtilities.invokeLater(new Runnable() {
     public void run() {
            // update label here
     }
});

【讨论】:

  • JFrame 在 WindowClosing 事件期间被冻结或暂停,因此不会显示任何组件更新。
  • 更新了我之前的评论。
【解决方案2】:

但我想添加在关闭的 JFrame 中的现有 JLabel 中提供关闭状态消息的功能

label.setText(....);
label.paintImmediately(label.getBounds());

侦听器中的代码在事件调度线程上执行,因此在所有侦听器代码执行完毕且 GUI 将关闭之前,GUI 无法重新绘制自身。

paintImmediately(...) 将允许组件绕过 RepaintManager 并立即绘制自己。

【讨论】:

  • 您的解释是有道理的,但我尝试使用paintImmediately() 没有任何运气。框架仍然没有在关闭事件中更新。
【解决方案3】:

我使用下面的代码在后台执行了关闭步骤,然后关闭了JFrame。

frame.addWindowListener(new WindowAdapter() {
    @Override
    public void windowClosing(WindowEvent e) {      
        SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
            @Override
            public Void doInBackground() {

                // shutdown steps go here and can update the JLabel text

                frame.dispose();
                return null;
            }
        };
        worker.execute();
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-29
    • 1970-01-01
    • 1970-01-01
    • 2013-08-04
    • 1970-01-01
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    相关资源
    最近更新 更多