/* related posts with thumb nails */

TextField or how to get input from the user in an applet:

Text Field is a GUI element used in applet to accept values from the user. This can be created by instantiating the class TextFiled of “java.awt” package as shown below.

TextField t1 = new TextField();

After creating the text field, we need to add it to applet using add() method. This is done in init() method of the applet.

add(t1);

To retrieve value from the text field, we use getText() method. But, this can return only string value. Depending on our requirements we might need to convert this to other data types. The syntax to get text value is shown below.

String val = t1. getText()

Example: The following program uses two text boxes to accept input from the user and a third text box is used to display the output i.e. the sum of the two values supplied through t1 and t2.





import java.applet.*;

import java.awt.*;

import java.awt.event.*;

public class Input extends Applet implements ActionListener

{

Button b1=new Button("ADD");

TextField t1=new TextField(10);

TextField t2=new TextField(10);

TextField t3=new TextField(10);

public void init()

{

t1.setText("0");

t2.setText("0");

t3.setText("0");

add(t1);

add(t2);

add(b1);

add(t3);

b1.addActionListener(this);

}

public void actionPerformed(ActionEvent ae)

{

int v1=Integer.parseInt(t1.getText());

int v2=Integer.parseInt(t2.getText());

t3.setText(String.valueOf(v1+v2));

}

}

Related Topics:

0 comments:

Post a Comment