Saturday, August 24, 2013

JTextField

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:
-JTextField()
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:
-getText():String
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.

Example:
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){
setTitle(title);
setSize(400,300);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contpane=getContentPane();
JTextField txt=new JTextField("This is a simple text.",20);
txt.getDocument().addDocumentListener(this);
txt.select(0, 10);
txt.setSelectedTextColor(Color.RED);
txt.setBorder(new BasicBorders.FieldBorder(Color.BLUE,Color.BLACK,Color.GREEN,Color.LIGHT_GRAY));
contpane.add(txt);
setVisible(true);

}

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