Saturday, August 24, 2013


JTextField component represents a text field that you can edit a single line of text. Unlike TextField, JTextField allows you to decorate the border of the text field, and specify the color of selected text. JTextField does not support password functionality. If you want password input, you need to use the JPasswordField instead.
The JTextField component can generate document events. A document event can be received by implementing the DocumentListerner interface and registering the listener by invoking the addDocumentListener(DocumentListener listener) method. The DocumentListener interface has three methods: removeUpdate(DocumentEvent e), insertUpdate(DocumentEvent e), and changedUpdate(DocumentEvent e) to be overridden.

Constructors of the JTextField class:
creates an empty text field.
-JTextField(int columns)
creates a text field with specified number of columns.
-JTextField(String text)
creates a text field with text.
-JTextField(String text,int columns)
creates a text field with text and specified number of columns.
Useful methods of the JTextField:
returns the text of the text field.
-setBorder(Border bd):void
specifies the border of the text field.
-select(int start,int end):void
selects the text in the text field from start to end positions.
-setSelectionColor(Color c):void
specifies the color of the selected part.
-setSelectedTextColor(Color c):void
specifies the selected text color.
-setText(String text):void
sets text to the text field.

import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.plaf.basic.BasicBorders;

class JTextFieldShow extends JFrame implements DocumentListener{
JTextFieldShow(String title){
setLayout(new FlowLayout());
Container contpane=getContentPane();
JTextField txt=new JTextField("This is a simple text.",20);
txt.getDocument().addDocumentListener(this);, 10);
txt.setBorder(new BasicBorders.FieldBorder(Color.BLUE,Color.BLACK,Color.GREEN,Color.LIGHT_GRAY));


public void removeUpdate(DocumentEvent e){

public void insertUpdate(DocumentEvent e){
System.out.println("a new character is added.");
public void changedUpdate(DocumentEvent e){


public class JFrameSwing {
public static void main(String[] args){
new JTextFieldShow("JTextField");

JTextField Swing

No comments:

Post a Comment