can*_*tas 1 java swing ping jprogressbar event-dispatch-thread
我不是新手,也是教授.在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();
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
我想将progressBar添加到Scan Operation,While Loop通过ping操作进行Scan操作.
请帮我.谢谢.抱歉语言不好
小智 5
对于我可以看到的关于您的帖子的内容,您试图在尝试在Swing中执行长时间运行的任务时保持UI响应.
不幸的是,Swing是一个单线程窗口系统,试图使长时间运行的任务将阻止UI.
从Java 1.6开始,Swing SDK包含一个名为SwingWorker的类,它允许在另一个线程中执行那种任务,同时为UI线程提供一个钩子,以便让用户了解进程的进展情况.
Java教程中给出了基本示例.
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);
}
}
Run Code Online (Sandbox Code Playgroud)
};
基本上,您可以定义自己的SwingWorker以在doInBackgroundMethod中执行Ping请求,并使用方法get()继续更新UI
以下是Java教程的链接:http://docs.oracle.com/javase/tutorial/uiswing/concurrency/simple.html
在Wikipedia中有关于如何使用SwingWorker的详细说明:http: //en.wikipedia.org/wiki/SwingWorker
我希望这可以帮助您解决问题.
最好的祝福.