首页  >  文章  >  Java  >  如何在Java中使用Swing Timer和SwingWorker进行高效的GUI任务管理?

如何在Java中使用Swing Timer和SwingWorker进行高效的GUI任务管理?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-24 05:31:30474浏览

How to Use Swing Timer and SwingWorker for Efficient GUI Task Management in Java?

在 GUI 中使用 Swing Timer 和 SwingWorker 执行重复和长时间运行的任务

在图形用户界面 (GUI) 中,维护应用程序的响应能力至关重要。执行长时间运行或重复的任务,例如网络调用或繁重的计算,如果处理不当,可能会冻结 UI。

用于重复任务的 Swing 计时器

对于任务对于需要定期重复的操作(例如,使用来自服务器的数据更新标签),Swing 提供了 Timer 类。计时器可以配置一个延迟和一个定义计时器触发时要执行的操作的 ActionListener。

用于长时间运行任务的 SwingWorker

SwingWorker 是一个 Swing扩展 SwingUtilities 的组件,专为需要较长时间的任务而设计。它允许您在后台线程中执行任务,同时保持 UI 响应。任务完成后,SwingWorker 通知主线程使用结果更新 UI。

示例:使用服务器 Ping 结果更新标签

演示结合使用 Timer 和 SwingWorker,请考虑以下代码片段:

<code class="java">import javax.swing.*;
import java.awt.event.*;
import java.net.Socket;

public class LabelUpdateExample {

    private static String hostnameOrIP = "stackoverflow.com";
    private static int delay = 5000;
    private static JLabel label = new JLabel("0000");

    public static void main(String[] args) {
        label.setFont(label.getFont().deriveFont(120f));

        ActionListener timerListener = new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new PingWorker().execute();
            }
        };
        Timer timer = new Timer(delay, timerListener);

        timer.start();
        JOptionPane.showMessageDialog(
                null, label, hostnameOrIP, JOptionPane.INFORMATION_MESSAGE);
        timer.stop();
    }

    private static class PingWorker extends SwingWorker {

        private int time;

        @Override
        protected Object doInBackground() throws Exception {
            time = pingTime();
            return new Integer(time);
        }

        @Override
        protected void done() {
            label.setText("" + time);
        }
    }

    private static int pingTime() {
        Socket socket = null;
        long start = System.currentTimeMillis();
        try {
            socket = new Socket(hostnameOrIP, 80);
        } catch (Exception weTried) {
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (Exception weTried) {}
            }
        }
        long end = System.currentTimeMillis();
        return (int) (end - start);
    }
}</code>

此代码创建一个 JLabel,用于显示指定主机的 ping 时间,并使用计时器每 5 秒更新一次。 ping 操作是在后台线程中使用 SwingWorker 执行的,以避免冻结 UI。 ping 完成后,SwingWorker 将使用结果更新标签,确保 GUI 在长时间运行的任务期间保持响应。

以上是如何在Java中使用Swing Timer和SwingWorker进行高效的GUI任务管理?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn