Thursday, July 8, 2010




A text field is a basic text control that enables the user to type a small amount of text.
The text field is editable. It is handy in cases 
where a single line of input is required or a little information is neede.
It is mostly used in forms and does most work on Event handling.There are certain methods which copies the contents of TextField whenever an action is fired.


JTextField has four types of constructors which are as follows


2.JTextField(String)  //Creates a TextField with initial text as String

3.JTextField(String,int)  //creates a TextField with length of cloumn being chars and default text is as String

4.JTextField(int)   //creates s TextField with length  of column being chars.

Note: Always try to specify the number of columns for each text field. If you do not specify the number of columns or a preferred size, then the field's preferred size changes whenever the text changes, which can result in unwanted layout changes.

Example:-Creating a form with JTextField

import javax.swing.*;
class textfield extends JFrame{
public static void main(String a[]){
  JFrame frame=new JFrame("JTextFieldDemo");
  JPanel panel=new JPanel();
  JTextField txt=new JTextField(10);
  JTextField txtf=new JTextField("Default",20);   //with default text written and size of 20 

We have several methods for getting and setting values from and to JTextField

1.String getText()

2.void setText(String)

Edit methods of JTextField component

1.void setEditable(boolean)  //set whether the text in the JTextField is editable or not

2. boolean isEditable()   //returns whether the tetfield is editable or not

For setting and getting the width of JTextField use

void setColumns(int)  //specifies the width of textfield

int getColumns()  //obtains number of columns of the TextField

For selecting whole field at once use following

void selectAll() 

For adding ActionListeners use following

void addActionListener(ActionListener)  //adds action listener

void removeActionListener(ActionListener)  //removes ActionListener

What next?

You can also bookmark this post using your favorite bookmarking service:

Related Posts by Categories

0 comments: to “ JTextField

Extension Factory Builder