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   
width.

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.


Programs

 

JTextFieldDemo

import java.util.*;
import javax.swing.*;
import java.awt.*;
class TextFieldDemo extends JFrame
{
public TextFieldDemo()
{
setSize(300,300);
setTitle("JTextFieldDemo");
setLayout(new FlowLayout(FlowLayout.CENTER,0,100));// used to center the panel in the 
                                                                                                                                                 frame   
setLocationByPlatform(true);
JPanel p=new JPanel();

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

TextFieldMain

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

class TextFieldMain
{
public static void main(String args[])
{
TextFieldDemo tfd=new TextFieldDemo();
tfd.setVisible(true);
tfd.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
 


Output:





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);
tf.setText("Hai");
  
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,












0 comments:

Post a Comment

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