Getting input from the User in Applets
https://www.computersprofessor.com/2016/12/getting-input-from-user-in-applets.html?m=0
|
|
Getting input
from the user
:
Applets work
in a graphical environment . Therefore , applets
treat inputs as text strings . we must
first create an
area of the
screen in which user can
type and edit
input items ( which may be any data
type) we can
do this by
using the TextField
class of the
applet package. Once
text fields are
created for receiving input,
we can type
the values in
the fields and
edit them if
necessary.
Next step
is to retrieve the
items from the
fields for display
of calculations, if any. Remember
the text fields
contain items in
string form. They need to be
converted to the write form before
they are used
in any applications . The
results are then converted back
to string for
display.
Program :
import java
. awt .* ;
import java. applet. * ;
public class
UserIn extends Applet
{
TextField text1, text2 ;
public
void init ( )
{
text1= new TextField
(8);
text2= new TextField
(8) ;
add( text1);
add ( text2);
text1. setText
(“ 0”) ;
text2. setText (“ 0”);
}
public
void point (
Graphics g)
{
int
x= 0, y =
0, z = 0 ;
String s1 ,s2 , s ;
g.drawString
(“ in put a
number in each box”,10, 50);
try
{
s1= text1.
getText ( ) ;
x= Integer.parseInt (s1) ;
s2 = text2 .getText
( );
y =
Integer.parseInt (s2);
}
catch (Exception ex)
{ }
z= x+ y
;
s= String .valueOf (z);
g. drawString
(“ The sum is
:” ,10,75);
g. drawString (s,100,75) ;
}
public boolean action ( Event event, Object object)
{
repaint ( ) ;
return true ;
}
}
Run the
applet UserIn using
the following Steps:
1.Type and
save the program
(.java file)
2.Complite the
applet (.class file)
3.write an
HTML document ( . html file)
<
html >
<
applet code = UserIn. class width =
300 height = 200 >
< /applet >
< / html >
4. use the appletviewer to
display the results.
when the applet
is up and
running, enter a number
in to each
text field box
displayed in the
applet area is
then press the
return key. Now
the applet computer
the of these
two numbers and
displays the result.
|
|
|
|