从ExecutorService更新JProgressBar [英] Update JProgressBar from ExecutorService

查看:137
本文介绍了从ExecutorService更新JProgressBar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java ICMP ping功能ping网关。为了执行快速ping,我使用ExectorService创建用于ping的线程。地址被ping(或没有)后我想在ping之后更新Jprogressbar。我有这个代码正在工作,但它在作业(ping线程)完成之前更新Jprogressbar。我希望在作业完成后更新jprogressbar。

I am pinging gateways using Java ICMP ping function. To perform fast pinging I am using ExectorService which creates threads for pinging. After address is pinged (or not) I want to update Jprogressbar after pinging. I have this code which is working but it updates Jprogressbar before job (ping thread) is finished. I want to update jprogressbar after job is finished.

private int NUM_THREADS = Runtime.getRuntime().availableProcessors();
ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS);
public void run() {
    int JProgressBarValue = 0;
    for (;GateWayKey<=GateWayKeyStop;GateWayKey++){
        ip="192.168."+GateWayKey+".1";
       exec.submit((new PingTask(ip,GateWayKey,true,scanFrameRefrence,ttl)));
       JProgressBarValue=(GateWayKey/GateWayKeyStop)*100;
       scanFrameRefrence.progressBar.setValue(JProgressBarValue);
       scanFrameRefrence.progressBar.repaint();
    }}


推荐答案

首先,Swing不能从事件派发线程外部使用组件。因此,更新进度条的代码必须包含在

First of all, Swing components may not be used from outside of the event dispatch thread. So, the code updating the progress bar must be enclosed inside

SwingUtilities.invokeLater(new Runnable() {
    @Override
    public void run() {
        scanFrameRefrence.progressBar.setValue(value);
    }
});

现在,回答这个问题。如果要在任务完成时更新进度条,更简单的方法是让任务在执行结束时更新进度条。

Now, to answer the question. If you want to update the progress bar when a task finishes, the easier way is to have the task itself update the progress bar when at the end of its execution.

另一个方法是使用 ExecutorCompletionService ,每个任务完成后都可以通知(由于阻塞队列)。

Another way is to use an ExecutorCompletionService, which can be notified (thanks to a blocking queue) when each task has finished.

另外,考虑发布实际的,编译代码和尊重Java命名约定:变量以一个小写字母。

Also, consider posting actual, compiling code, and respecting Java naming conventions: variables start with a lower-case letter.

这篇关于从ExecutorService更新JProgressBar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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