import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class Exm4 extends Applet implements ActionListener
{
TextField textField1 = new TextField(); //input textField
TextField textField2 = new TextField(); //output textField
Label label1 = new Label();
Label label2 = new Label();
Button button1 = new Button();
public void init()
{
setLayout(null); //free layout
setSize(300,300); //size of this applet
add(textField1);
textField1.setFont(new Font("Dialog", Font.PLAIN, 20));
textField1.setBounds(100,50,150,40);
add(textField2);
textField2.setFont(new Font("Dialog", Font.PLAIN, 20));
textField2.setBounds(100,120,150,40);
add(label1);
label1.setText("n = ");
label1.setFont(new Font("Dialog", Font.PLAIN, 20));
label1.setBounds(20,50,60,40);
add(label2);
label2.setText("المجموع = ");
label2.setFont(new Font("Dialog", Font.PLAIN, 20));
label2.setBounds(20,120,60,40);
add(button1);
button1.setLabel("احسب");
button1.setBackground(java.awt.Color.lightGray);
button1.setFont(new Font("Dialog", Font.PLAIN, 20));
button1.setBounds(80,200,120,40);
button1.addActionListener(this);
}
public void actionPerformed(ActionEvent event)
{
Object object = event.getSource();
String str;
int n,sum;
if (object == button1){
// get text from textfield
str=textField1.getText();
// convert string to integer
n=Integer.parseInt(str);
sum=calculate(n);
// convert integer to string
str=Integer.toString(sum);
//set text to textfield
textField2.setText(str);
}
}
public int calculate(int n){
int i; // index
int a; // i-th term
int s=0; // sum of the sequence
for(i=1;i<=n;i++){
a=i; //a(i)=i
s=s+a; // S(i+1)=S(i)+a(i)
}
return s;
}
}
|