Wednesday, February 11, 2009
IP Scanner 003 - using SwingWorker class (concurrent GUI)
/*
* GUI version of IPScanner
* Scans IP networks using ping
* uses SwingWorker class to
* concurrently update GUI
* by Paul Chin, Feb 11, 2009
*/
package ipscannergui;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import javax.swing.*;
public class IPScannerGui extends JFrame {
private JButton btnStart;
private JTextField tfIP;
private JLabel lbIP;
private JTextArea taOutput;
private JScrollPane jsp;
//SwingWorker[] worker = new SwingWorker[100];
public static void main(String[] args) {
IPScannerGui sg = new IPScannerGui(); // create ButtonFrame
sg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sg.setSize(500, 400); // set frame size
sg.setVisible(true); // display frame
}
public IPScannerGui() {
super("IP Scanner 003");
setLayout(new FlowLayout()); // set frame layout
lbIP = new JLabel("Enter network (eg 118.100.118)");
tfIP = new JTextField("192.168.1", 20);
btnStart = new JButton("Start");
taOutput = new JTextArea(20, 40);
jsp = new JScrollPane(taOutput);
add(lbIP);
add(tfIP);
add(btnStart);
add(jsp);
ButtonHandler handler = new ButtonHandler();
btnStart.addActionListener(handler);
}
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnStart) {
try {
for (int i = 1; i < w =" new">() {
public String doInBackground() throws IOException {
String s;
s = doScan(ip);
return s;
}
public void done() {
String t = null;
try {
t = get();
taOutput.append(t);
} catch (Exception x) {
x.printStackTrace();
}
}
};
w.execute();
}
private String doScan(String ip) throws IOException {
String line;
Process p = Runtime.getRuntime().exec("cmd /c ping " + ip + " -n 1");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
if (line.indexOf("Reply") > -1) {
System.out.println(line);
input.close();
return line + "\n";
}
}
return ip + " not found\n";
}
}