Progress bar not updating during a loop

痴心易碎 提交于 2020-03-06 09:29:10

问题


My progress bar doesn't update until the loop has finished? Why is this?

for (String theURL : IPArray) {
    URL url = new URL(theURL);
    InetAddress address = InetAddress.getByName(url.getHost());
    String temp = address.toString();
    String IP = temp.substring(temp.indexOf("/") + 1, temp.length());
    URLArray.add(IP);
    Progress.percentage = (URLArray.size() * 100) / Progress.totalToDo;
    Progress.ipProgress.setString(Progress.percentage + "%");
    Progress.ipProgress.setValue(Progress.percentage);
    Progress.ipProgress.repaint();
    result += IP + System.getProperty("line.separator");
}

It will only update after it gets past the loop and not during it.


回答1:


Needed a new thread.

new Thread(new Runnable() {
    String result = "";

    public void run() {
        for (String theURL : IPArray) {
            try {
                URL url = new URL(theURL);
                InetAddress address = InetAddress.getByName(url.getHost());
                String temp = address.toString();
                String IP = temp.substring(temp.indexOf("/") + 1, temp.length());
                URLArray.add(IP);
                Progress.percentage = (URLArray.size() * 100) / Progress.totalToDo;
                Progress.ipProgress.setString(Progress.percentage + "%");
                Progress.ipProgress.setValue(Progress.percentage);
                Progress.ipProgress.repaint();
                result += IP + System.getProperty("line.separator");
            } catch (Exception e) {
                if ("www.".equals(e.getMessage())) {
                    JOptionPane.showMessageDialog(
                            null, "Incorrect URL. Usage: http://www.URL.com\nError = Space! Can't use gaps in list.", "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
        IPFrame.textAreaIP.setText(result);
        GEOLookup.check(IPFrame.textAreaIP.getText());
    }
}).start();


来源:https://stackoverflow.com/questions/17923509/progress-bar-not-updating-during-a-loop

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