进度条在循环期间不更新

时间:2013-07-29 12:02:43

标签: java swing concurrency event-dispatch-thread jprogressbar

我的进度条在循环结束前不会更新?这是为什么?

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

它只会在经过循环后更新,而不是在循环过程中更新。

1 个答案:

答案 0 :(得分:0)

需要一个新线程。

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