Java 使用长时间运行任务的结果重复更新JLabel

Java 使用长时间运行任务的结果重复更新JLabel,java,swing,jlabel,ping,event-dispatch-thread,Java,Swing,Jlabel,Ping,Event Dispatch Thread,我正在编写一个程序,不断ping服务器。我编写了代码来检查它一次,并将ping放在JLabel中,然后将其放在名为setPing()的方法中 这是我的密码 这很有效,但只做了一次,所以我做了: private void formWindowOpened(java.awt.event.WindowEvent evt) { for(;;){ setPing(); } } 但这甚至不是第一次起

我正在编写一个程序,不断ping服务器。我编写了代码来检查它一次,并将ping放在
JLabel
中,然后将其放在名为
setPing()的方法中

这是我的密码

这很有效,但只做了一次,所以我做了:

private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
for(;;){
    setPing();
    }
}           
但这甚至不是第一次起作用

我没有使用设置方法,因为它太长,所以它是:

public String setPing(){
Runtime runtime = Runtime.getRuntime(); 
try{
    Process process = runtime.exec("ping lol.garena.com");
InputStream is = process.getInputStream(); 
InputStreamReader isr = new InputStreamReader(is); 
BufferedReader br = new BufferedReader(isr); 
String line; 
while ((line = br.readLine()) != null) {
    int i = 0;
      i = line.indexOf("Average");
    if(i > 0){  
    String finalPing = "";
    line.toCharArray();
    try
    {
        finalPing = "";
        for(int x = i; x < i + 17; x++)
        {
            finalPing = finalPing + (line.charAt(x));
        }
    }catch(IndexOutOfBoundsException e)
    {
        try
        {
            finalPing = "";
            for(int x = i; x < i + 16; x++)
            {
                finalPing = finalPing + (line.charAt(x));
            }
        }catch(IndexOutOfBoundsException f)
        {
            try
            {
                finalPing = "";
                for(int x = i; x < i + 15; x++)
                {
                    finalPing = finalPing + (line.charAt(x));
                }
            }catch(IndexOutOfBoundsException g){}
        }
    }
    String final1Ping = finalPing.replaceAll("[^0-9]", "");
    return final1Ping;
    }
} 
}catch(IOException e){
}
return "";
}
你可以用一个小盒子。问题是您正在阻塞主线程,从而阻塞了程序。要解决此问题,请启动后台
线程
,以重复更新组件

(注意:您需要在上更新GUI组件,因此请使用)


使用Swing
计时器执行重复任务,使用
SwingWorker
执行长时间运行的任务。例如,在以下两种情况下-它使用
计时器
SwingWorker
中重复执行“长时间运行”任务(ping)

import java.awt.event.*;
import javax.swing.*;
import java.net.Socket;

public class LabelUpdateUsingTimer {

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

    LabelUpdateUsingTimer() {
        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();
    }

    class PingWorker extends SwingWorker {

        int time;

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

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

    public 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);
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                new LabelUpdateUsingTimer();
            }
        };
        SwingUtilities.invokeLater(r);
    }
}
有关事件调度线程以及在GUI中执行长时间运行或重复任务的更多详细信息,请参阅

此代码使用从重复任务调用的
SwingWorker
(使用基于Swing的
计时器重复更新
JLabel
)组合长时间运行的任务(“ping”服务器)

import java.awt.event.*;
import javax.swing.*;
import java.net.Socket;

public class LabelUpdateUsingTimer {

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

    LabelUpdateUsingTimer() {
        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();
    }

    class PingWorker extends SwingWorker {

        int time;

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

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

    public 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);
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                new LabelUpdateUsingTimer();
            }
        };
        SwingUtilities.invokeLater(r);
    }
}

我太懒了。正在等待有人发布此消息:-@peeskillet需要一定数量的错误或过于复杂的答案才能达到我的“我只想‘坐在这里看着集群’的极限。”我不明白。你能告诉我如何和在哪里调用我的方法setPing()吗?是的,我确实替换了
label.setText(“+rand.nextInt(1000))使用
setPing()
但是这是一个非静态的方法,因为它更新了jLableloh,等等,我发现了!谢谢!好的,我做了这个,它有点效果。我将设置方法从
public void
更改为
public String
,现在不再更改jLabel的文本,而是将ping作为字符串返回。现在,当我在代码中替换
refToJLabel.setText(Math.random())System.out.println(setPing())进行编码>操作,在控制台中连续打印ping。但是当我放置
jLabel1.setText(setPing())时它什么也不做。在这种情况下“工作”意味着“失败”。它应该完美地工作。我注意到这段代码没有延迟
线程
循环,所以我猜对标签的大多数更新都会被忽略。
(new Thread((new Runnable(){
    @Override
    public void run(){
        while(true){
            SwingUtilities.invokeLater(new Runnable(){
                @Override
                public void run(){
                    refToJLabel.setText(Math.random());
                }
            });
        }
    }
}))).start();
import java.awt.event.*;
import javax.swing.*;
import java.net.Socket;

public class LabelUpdateUsingTimer {

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

    LabelUpdateUsingTimer() {
        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();
    }

    class PingWorker extends SwingWorker {

        int time;

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

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

    public 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);
    }

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                new LabelUpdateUsingTimer();
            }
        };
        SwingUtilities.invokeLater(r);
    }
}