Add to Google Reader or Homepage

JTextField - An Example

How to create and use JTextField 

In an user interface design,a text field provides a way to interact with the user either by prompting the user to enter an input  or by displaying some information in the textfield.

In this post we are going to see how to create a textfield and use it in our application.

To create a text field you need to create an object of the JTextField class in the javax.swing package as follows.

JTextField tf=new JTextField(20);

The argument value "20" in the above statement specifies the width of the TextField.

JTextField class has four constructors which are of great concern to us. They are...

1. JTextField tf=new JTextField() - creates a text field with width "0"

2. JTextField tf=new JTextField(int columns)-creates a text field with the given   

3. JTextField tf=new JTextField(String str,int columns) ;

creates a text field with the given width and displays the string given in the first argument.

4. JTextField tf=new JTextField(String str)

creates a text field displaying the string with the length of the string as the size of the text field.




import java.util.*;
import javax.swing.*;
import java.awt.*;
class TextFieldDemo extends JFrame
public TextFieldDemo()
setLayout(new FlowLayout(FlowLayout.CENTER,0,100));// used to center the panel in the 
JPanel p=new JPanel();

JLabel lb=new JLabel("INPUT1");
JTextField tf=new JTextField();
tf.setText("Hi!Enter the input here.. ");


import java.util.*;
import javax.swing.*;

class TextFieldMain
public static void main(String args[])
TextFieldDemo tfd=new TextFieldDemo();


JTextField class has two important methods namely,

void  setText(String str) - to display a particular text in the text field say for an example,

JTextField tf=new JTextField(20);
String getText ()-  to retrieve text from the particular text field like as follows,

String s=tf.getText();

You can also dynamically change the "size" of the text field using setColumns(int width).

for example tf.setColumns(10); will  provide a output like this,

java errors and exceptions © 2010 | Designed by Chica Blogger | Back to top