Listing 5: A more elaborate Java applet
import java.applet.*;
import java.io.*;
import java.net.*;
import java.awt.*;
public class Simple extends Applet {
List ItemList;
TextField Message;
Button BtnOK;
Button Btn;
Socket SrvSock;
public void init() {
setLayout(new BorderLayout());
ItemList = new List( );
BtnOK = new Button( "OK" );
add( "North", ItemList );
Panel p = new Panel( );
p.setLayout( new BorderLayout( ) );
add( "Center", p );
Panel p1 = new Panel( );
p1.setLayout( new FlowLayout( ) );
p1.add( "Left", new Button( "Left" ) );
p1.add( "Center", new Button( "Center" ) );
p1.add( "Right", new Button( "Right" ) );
p.add( "North", p1 );
p.add( "South", BtnOK );
Message = new TextField( );
p.add( "Center", Message );
}
public boolean action(Event evt, Object arg) {
if( evt.target instanceof Button ) {
String BtnName = ((Button)evt.target).getLabel( );
if( BtnName == "OK" ) {
InputStream MyInput;
try {
SrvSock = new Socket( "localhost", 13 );
}
catch( Exception e) {
e.printStackTrace( );
return true;
}
try {
MyInput = SrvSock.getInputStream( );
}
catch( Exception e) {
e.printStackTrace( );
return true;
}
byte NetDate[] = new byte[80];
char NetChar[] = new char[80];
int NetRead;
try {
NetRead = MyInput.read( NetDate );
}
catch( Exception e) {
e.printStackTrace( );
return true;
}
int i = 0;
NetChar[NetRead] = (char)0;
while( NetRead > 0 ) {
NetChar[i] = (char)NetDate[i];
i++;
NetRead--;
}
String MsgTxt = new String( NetChar );
Message.setText( MsgTxt );
try {
SrvSock.close( );
}
catch( Exception e) {
e.printStackTrace( );
return true;
}
}
else {
ItemList.addItem( BtnName );
}
}
return true;
}
}
|