所以我正在研究一个次要的GUI,从命令行ping从IP列表中选择的IP。我有这个工作,并通过getInputStream返回到输出。
这是我运行ping的代码:
String pingResult = "";
try {
Runtime r = Runtime.getRuntime();
Process p = r.exec("ping " + IPAddressList.getSelectedValue());
try (BufferedReader in = new BufferedReader(new InputStreamReader
(p.getInputStream()))) {
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
pingResult += inputLine;
}
}
}//try
catch (IOException e) {
System.out.println(e);
}
我现在需要做的是从一个IP列表(存储在一个带有DefaultModel名称机器的Jlist中),我需要不断允许列表的IP被ping并且列表要更新(我已经了解了如何进行更新)。
我不知道如何使用上面的一些代码启动此循环并使其保持运行。此外,在运行时,我需要确保GUI可以执行其他操作,例如:从列表中删除IP,向列表中添加IP,ping单个IP等等。
感谢您的帮助。
答案 0 :(得分:0)
您可以在不同的线程上启动try循环中的所有内容,使其独立运行,然后您可以继续运行时执行任何操作(添加/删除IP)。
按照本教程进行操作,您将找到所需的大部分内容: Java Tutorials: Concurrency
答案 1 :(得分:0)
您需要在后台线程中启动ping操作。使用SwingWorker
可能是实现此目的的最简单方法。你可以相当容易地传递一个IP地址列表,它将在后台运行,每个地址ping,然后将中间结果传递回GUI。关于SwingWorker
类的一个好处是它确保在Swing的主事件派发线程中处理结果,这样你就不需要做任何额外的事情来处理它。
Javadoc很好地概述了它的用法:
http://docs.oracle.com/javase/7/docs/api/javax/swing/SwingWorker.html
以下是一个粗略的起点。然后,您将实例化它并调用其execute()
方法来启动后台进程。
class PingWorker extends SwingWorker<Void, PingResult> {
private List<IpAddress> addresses;
public PingWorker(List<IpAddress> addresses) {
this.addresses = addresses;
}
@Override
protected Void doInBackground() throws Exception {
for (IpAddress address : addresses) {
// run ping code and build result
publish(new PingResult(address /* other result params here */));
}
// no need to return anything as we are processing the intermediate results
return null;
}
@Override
protected void done() {
// pings are complete, update GUI to reflect this
}
@Override
protected void process(List<PingResult> results) {
for (PingResult result : results) {
// update GUI with the result of the ping such as your table model
}
}
}