import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/** When 'import', only classes and interfaces are imported, if you want to
* import the sub-package just like java.awt.event, have to import one more time
*/
public class NumSumUI extends Applet implements ActionListener
/**
* 'extends' mean create a ingeritaged class NumSumUI according to superclass Applet,
* in the mean time, we also use an interface 'ActionListener' by keyword 'implements'
* to moniter all the events happened in an applet.
*/
{
/** First of all, define all the Label, Button, TextField */
Label l1,l2,l3,l4;
TextField tf1,tf2,tf3;
Button bCon,bSum;
String msg="";
String str_tf3;
int nSum;
/** Applet Initializing */
public void init()
{
/**
* After 'public void init()', define Layout first by 'setLayout'.
* There are five layouts: FlowLayout(default), GridLayout, CardLayout, BorderLayout, null.
* Here, we using 'null' to init the Applet's Layout.
*/
setLayout(null);
l1 = new Label("ConSum v1");
l2 = new Label("Str 1:");
l3 = new Label("Str 2:");
l4 = new Label("Result:");
tf1 = new TextField();
tf2 = new TextField();
tf3 = new TextField();
bCon = new Button("TextCon !");
bSum = new Button("NumSum !");
/**
* After create INSTANCES for all the elements of the applet
* It's time to size it. We use setBounds(x,y,width,height) coordinate sys to define the place and size.
*/
l1.setBounds(60,10,90,20);
l2.setBounds(20,50,50,20);
tf1.setBounds(80,50,80,20);
l3.setBounds(20,90,50,20);
tf2.setBounds(80,90,80,20);
l4.setBounds(20,130,50,20);
tf3.setBounds(80,130,80,20);
bCon.setBounds(10,160,90,25);
bSum.setBounds(100,160,90,25);
/**
* Then, we have to add everything we created and defined above to the layout. Otherwise, it will hidden.
*/
add(l1);
add(l2);
add(l3);
add(l4);
add(tf1);
add(tf2);
add(tf3);
add(bCon);
add(bSum);
/**
* Everytime we click, a performance is detected, so we add an ActionListener to the button itself,(this).
*/
bCon.addActionListener(this);
bSum.addActionListener(this);
}
/**
* Next, we are about to define what Java should does when we press the buttons.
*/
public void actionPerformed(ActionEvent ae)
{
String str = ae.getActionCommand();
if(str.equals("TextCon !"))
{
tf3.setText(tf1.getText()+tf2.getText());
str_tf3 = tf3.getText();
msg = "The result of TextConc is " + str_tf3;
}
else if(str.equals("NumSum !"))
{
nSum=Integer.parseInt(tf1.getText()) + Integer.parseInt(tf2.getText());
tf3.setText(String.valueOf(nSum));
msg = "The sum of all the numbers is: " + nSum;
}
repaint();
}
public void paint(Graphics gfc)
{
gfc.drawString(msg, 10, 200);
}
}
/*
<applet code=NumSumUI width=220 height=250>
</applet>
*/