TextField in Java




TextField in Java (AWT)

The object of a TextField class is a text component that allows the editing of a single line text. It inherits TextComponent class.





AWT TextField Class Declaration:-

         public class TextField extends TextComponent  



Java AWT TextField Example:-

TextField t1,t2;  

    t1=new TextField("Welcome to my  Blog.");  

    t1.setBounds(50,100, 200,30);



To use a TextField for Input

1.    Declare a TextField as an instance variable. Reason: If it's an instance variable, it can be seen in all methods in the class.

2.    Assign an initial value to this variable by calling the JTextField constructor. Example:

           TextField yourInpuFieldt = new TextField(16);

3.    Add the text field to a container.

           content.add(yourInputField);

4.    Input is done by calling the getText().

1.    Get the string in the text field by calling yourTextField.getText() method whenever you need it. This is probably the most common way.

                    String x = yourInputField.getText();

2.    Attach an action listener to the text field. It is called whenever the user types Enter in that field. The listener can then get the text and process it.


To use a TextField for Output:-


Using a TextField for output is almost the same as for input, but . . .

1.    Set the text field with yourTextField.setText(someString)

2.    If it's only for output, call .setEditable(false) so the user can't change the field.

     Here is the sequence.

1.    Declare and initialize a TextField as a field variable (instance variable). Example:

          TextField myOutput = new TextField(16);

           You can also set the initial value in the field

            TextField myOutput = new TextField("someInitialValue", 20);

2.    Add the text field to a container or frame.

       For example, to add it to Panel p.

                             p.add(myOutput);

                        to add it to Frame f;

                              f.add(myOutput);

3.    Setting the value of the text field. Whenever you want put a string value in the text field, call myOutput.setText("Some text").

              myOutput.setText("some text");







// Program to illustrate the use of Text Field in Java.

import java.awt.*;

public class textfield{

    public static void main(String args[])

    {

        Frame f=new Frame("program 5");

        TextField t1=new TextField("this is the example of textfield");

        t1.setBounds(50,100,50,50);

        f.add(t1);

        f.setSize(600,600);

        f.setVisible(true);

    }

  }

Output :-

                                                     for any query feel free to comment.

Comments