package com.xie.netcorse2;
import java.awt.Button;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.InputStreamReader;
@SuppressWarnings("serial")
public class Ping2 extends Frame{
Label label1;
TextField tf0;
TextArea tf1;
Button btnSend,btnClear;
public static void main(String[] args){
new Ping2();
}
Ping2(){
setTitle("ping的java调用");
setLayout(null);
setBounds(400, 400, 320, 240);
label1=new Label("请输入ping的地址:");
label1.setBounds(0, 40, 100, 20);
tf0=new TextField("127.0.0.1");
tf0.setBounds(100, 40, 120, 20);
tf1=new TextArea(5, 1);
tf1.setBounds(0, 60, 320, 160);
btnSend=new Button("ping");
btnSend.setBounds(280, 220, 40, 20);
btnClear=new Button("清空");
btnClear.setBounds(250, 40, 40, 20);
btnClear.addActionListener(new ClearText());
btnSend.addActionListener(new myMonitor());
add(label1);
add(tf0);
add(btnSend);
add(btnClear);
add(tf1);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
setResizable(false);
setVisible(true);
}
class ClearText implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
tf0.setText("");
}
}
class myMonitor implements ActionListener{
private String host=null;
@Override
public void actionPerformed(ActionEvent e) {
host=tf0.getText().trim();
tf1.setText(host);
ping(host);
}
private void ping(String ip_host){
String s = "";
Process process;
try
{
process = Runtime.getRuntime().exec( "cmd /c " + "ping"+" "+ip_host);
BufferedReader br = new BufferedReader( new InputStreamReader(
process.getInputStream() ) );
while ( ( s = br.readLine() ) != null ){
tf1.setText(tf1.getText()+"/n"+s);//textArea中换行"/r/n"和"/n"
}
process.waitFor();
} catch ( Exception ex )
{
ex.printStackTrace();
}
}
}
}