使用长时间运行任务的结果重复更新 JLabel [英] Update JLabel repeatedly with results of long running task

查看:29
本文介绍了使用长时间运行任务的结果重复更新 JLabel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing a program that constantly pings a server. I wrote the code to check it once and put the ping in a JLabel and put it in a method called setPing().

这是我的代码

private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
    setPing();
}           

那行得通,但只做了一次,所以我做到了:

That worked but only did it once, so I did:

private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
for(;;){
    setPing();
    }
}           

但这在第一次甚至不起作用.

But this doesn't even work for the first time.

我没有放setPing方法,因为太长了所以放在这里:

I didnt put the setPing method because it was too long so here it is:

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 "";
}

更新以防万一这很重要,我使用 netbeans.我创建了一个表单并将此代码放在 formWindowOpened evt 中,而不是在 main 中调用它:

UPDATE Just in case this is important, Im using netbeans. I created a form and put this code in the formWindowOpened evt instead of calling it in main:

private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  

    ActionListener timerListener = new ActionListener() {

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


        timer.start();
        jLabel1.setText(label.getText());
        timer.stop();
 // TODO add your handling code here:
}                                 

class PingWorker extends SwingWorker {

    int time;

    @Override
    protected Object doInBackground() throws Exception {
        time = pingTime("lol.garena.com");
        return new Integer(time);
    }

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

public JComponent getUI() {
    return label;
}

public static int pingTime(String hostnameOrIP) {
    Socket socket = null;
    long start = System.currentTimeMillis();
    try {
        socket = new Socket(hostnameOrIP, 80);
    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (IOException e) {
            }
        }
    }
    long end = System.currentTimeMillis();
    return (int) (end - start);
}

推荐答案

使用 Swing Timer 重复任务 &一个 SwingWorker 用于长时间运行的任务.例如.以下两者 - 它使用 TimerSwingWorker 中重复执行长时间运行"任务(ping).

Use a Swing Timer for repeating tasks & a SwingWorker for long running tasks. E.G. of both below - it uses a Timer to repeatedly perform a 'long running' task (a ping) in a SwingWorker.

有关事件调度​​线程和在 GUI 中执行长时间运行或重复的任务.

See Concurrency in Swing for more details on the Event Dispatch Thread and doing long running or repeating tasks in a GUI.

此代码使用 SwingWorker 组合了一个长时间运行的任务('ping' 服务器),该任务使用 Swing 从重复任务(随着时间重复更新 JLabel)调用基于定时器.

This code combines a long running task ('pinging' a server) using SwingWorker invoked from a repeating task (updating the JLabel repeatedly with the times) using a Swing based Timer.

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

这篇关于使用长时间运行任务的结果重复更新 JLabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆