In this applet, we can add two numbers using GUI, where we take input from the user through text fields.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.applet.*;//Importing java.applet public class MyApplet extends Applet { TextField txt1, txt2; public void init()//Initializing our applet { txt1 = new TextField(""); //Creates a textfield 'txt1' txt2 = new TextField(""); //Creates a textfield 'txt2' setBackground(Color.CYAN);//Setting background color to CYAN add(txt1); //Adds textfield 'txt1' to your applet add(txt2); //Adds textfield 'txt2' to your applet } public void paint(Graphics obj)//Paint method to display our message { String s1 = txt1.getText(); //Fetching data from text field 1. String s2 = txt2.getText(); //Fetching data from text field 2. int num1=0, num2 = 0, num3; //Declaring 3 integer variables num1 = Integer.parseInt(s1); //Parsing the string value of text field 1 to integer num2 = Integer.parseInt(s2); //Parsing the string value of text field 2 in integer num3 = num1 + num2; //Performing addition String s3 = String.valueOf(num3); //Converting the result from integer to string obj.drawString("Result:", 40, 50); obj.drawString(s3, 50, 50);//To display the result } } |
Vlad
Latest posts by Vlad (see all)
- Code jam “Tic-Tac-Toe-Tomek” solution in java - April 19, 2013
- Code jam “Minimum Scalar product” solution in java - March 18, 2013
- Code jam Store Credit solution in java - March 10, 2013