Update JProgressBar from ExecutorService

时间秒杀一切 提交于 2019-12-02 15:43:30

问题


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

回答1:


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.

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

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



来源:https://stackoverflow.com/questions/17640244/update-jprogressbar-from-executorservice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!