Text fields control in Java AWT:
Text components can be used for accepting text input from the user. There are two classes available in text components. They are TextFields and TextAreas.The TextField control in java awt is a class which can be used to enter a single line of the text.
A constructor of TextField control:
The TextField class has four constructors. They are:
TextField()
it is used to create an Empty text field.
TextField(String str)
It is used to create a text field with a specified string.
TextField(int colsize)
It is used to create a text field with a specified number of columns.
TextField(String str,int colsize)
it is used to create a text field with the specified string and the specified number of columns.
Methods:
The most commonly used text field method is as follows:
void addActionListener(ActionListener Listener)
This method is used to configure an event Handler for the text field.
String getText()
This method is used to return the text in the fields.
void setEditable(Boolean state)
The setEditable()method is used to set a field as being editable or fixed.if the state is true, the text field may be edited. if the state is false, it cannot be edited.
void selectAll()
The selectAll() method is used to select all the text in the text field.
void select(int beg int end)
The select() method is used to select the text from the beginning index to the ending index.
void setText(String str)
The setText() method is used to set the text for the field.
void setFont(Font strFont)
It is used to set the font for the text field.
void setBackground(Color bgcolor)
This method is used to set the background color of the text field.
Sample Program:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/* <applet code="TextFielddemo" width=500 height=500>
</applet> */
public class TextFielddemo extends Applet implements ActionListener
{
TextField t1,t2;
LayoutManager Layout;
public TextField demo
{
t1=new TextField("Input",40);
t2=new TextField("Text entered above appear here",40);
Layout=new FlowLayout();
setBackground(Color.cyan);
t1.setBackground(Color.yellow);
t2.setForeground(Color.red);
setLayout(Layout);
add(t1);
add(t2);
t2.setEditable(false);
t1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
t2.setText(t1.getText());
}
}