Google

Wednesday, February 11, 2009

IP Scanner 002 - using ExecutorService (concurrent GUI)



/*
* GUI version of IPScanner
* Scans IP networks using ping
* Concurrent GUI update
*/
package ipscannergui;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.concurrent.*;
import javax.swing.*;

public class IPScannerGui extends JFrame {

private JButton btnStart;
private JTextField tfIP;
private JLabel lbIP;
private JTextArea taOutput;
private JScrollPane jsp;

public static void main(String[] args) {
IPScannerGui sg = new IPScannerGui();
sg.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
sg.setSize(500, 400);
sg.setVisible(true);

}

public IPScannerGui() {
super("IP Scanner 002");
setLayout(new FlowLayout()); // set frame layout
lbIP = new JLabel("Enter network (eg 118.100.118)");
tfIP = new JTextField("118.100.118", 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) {
IPScanner[] ips = new IPScanner[254];

ExecutorService runner = Executors.newFixedThreadPool(254);
for (int i = 1; i < 20="=" ip =" ipadd;" p =" Runtime.getRuntime().exec(" input =" new" line =" input.readLine())"> -1) {
//System.out.println(line);
final String r = line + "\n";
SwingUtilities.invokeLater(new Runnable() {

public void run() {
taOutput.append(r);
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
}

}
}
}