如何添加进度条? Java的

时间:2013-12-13 19:42:34

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

我不是新手,也是教授。在Java上。我正在尝试将progressBar添加到我的应用程序中,该应用程序使用 isReachable()方法将ping发送到给定的ip范围。 我该如何添加?我不知道任务和线程用法。我阅读了有关progressBar的java文档,但我无法添加。 这是我的代码

final JButton btnScan = new JButton("Scan");
btnScan.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        Runtime rt = Runtime.getRuntime();
        String lastIpCheck = " "; 
        String ip = textField.getText();
        String lastIp = textField_1.getText();
        String parsedOutput=  " ";
        InetAddress inet;
        boolean reachable;

        while(!(lastIpCheck.equalsIgnoreCase(lastIp))) {
            try {
                inet = InetAddress.getByName(ip);
                reachable = inet.isReachable(2500);
                String output=null;
                lastIpCheck = f.nextIpAddress(ip);

                if(reachable) {
                    model.addElement(ip);
                }

                ip = lastIpCheck;

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
});

我想将progressBar添加到Scan Operation,While Loop通过ping来执行Scan操作。

请帮帮我。 谢谢。 对不起,语言不好

1 个答案:

答案 0 :(得分:5)

有关您的帖子的内容,您尝试在Swing中执行长时间运行的任务时保持UI响应。

不幸的是,Swing是一个单线程窗口系统,试图制作长时间运行的任务会阻止UI。

从Java 1.6开始,Swing SDK包含一个名为SwingWorker的类,它允许在另一个线程中执行那种任务,同时为UI线程提供一个钩子,以便让用户了解流程的进展情况。

Java Tutorial中给出了基本示例。

SwingWorker worker = new SwingWorker<ImageIcon[], Void>() {
@Override
public ImageIcon[] doInBackground() {
    final ImageIcon[] innerImgs = new ImageIcon[nimgs];
    for (int i = 0; i < nimgs; i++) {
        innerImgs[i] = loadImage(i+1);
    }
    return innerImgs;
}

@Override
public void done() {
    //Remove the "Loading images" label.
    animator.removeAll();
    loopslot = -1;
    try {
        imgs = get();
    } catch (InterruptedException ignore) {}
    catch (java.util.concurrent.ExecutionException e) {
        String why = null;
        Throwable cause = e.getCause();
        if (cause != null) {
            why = cause.getMessage();
        } else {
            why = e.getMessage();
        }
        System.err.println("Error retrieving file: " + why);
    }
}

};

基本上,您可以定义自己的SwingWorker以在doInBackgroundMethod中执行Ping请求,并使用方法get()

继续更新UI

以下是Java教程的链接:http://docs.oracle.com/javase/tutorial/uiswing/concurrency/simple.html

在Wikipedia中有关于如何使用SwingWorker的详细说明: http://en.wikipedia.org/wiki/SwingWorker

我希望这可以帮助您解决问题。

最诚挚的问候。

相关问题