使用 InetAddress 多次 Ping 会使 GUI 无响应

Pinging multiple times using InetAddress makes GUI unresponsive

我的程序是无限地 ping 主机并将每个 ping 结果显示在 GUI 上 RED/GREEN。这里,'res' 是一个根据 ping 结果更改其文本和背景的标签。

问题是当我使用 while() 时,GUI 变得没有响应并且标签的颜色没有改变,而 ping 服务继续。我该如何解决这个问题??

while (true) {
        try {
            boolean status = InetAddress.getByName(host).isReachable(timeOut);

            if (status == true) {
                res.setText("ON");
                res.setBackground(Color.GREEN);
            } else {
                res.setText("OFF");
                res.setBackground(Color.RED);
            }
        } catch (IOException ex) {
        }

先看看 Concurrency in Swing

基本上,根据您的描述,您正在阻塞事件调度线程,阻止它处理新事件,包括绘制事件。

Swing 也不是线程安全的,这意味着您不应从 EDT 上下文之外更新 UI。

在这种情况下,您可以使用 SwingWorkerdoInBackground 方法中执行物理 "ping" 并利用 publish/process 方法来更新 UI.

有关详细信息,请参阅 Worker Threads and SwingWorker