In this tutorial you will learn about the Swing JTextField and its application with practical example.
Swing JTextField
JTextField is a Lightweight single line component which allows user for editing. It extends JTextComponent and implements SwingConstants.
JTextField Class Declaration
1 |
public class JTextField extends JTextComponent implement SwingConstant |
JTextField Constructor
Some commonly useable constructors are listed below.
JTextField : This constructor is used to construct new Text Field.
JTextField(Document doc,String text, int columns): This constructor is used to construct a Text Field which used the given text storage model and the given number of columns.
JTextField(int columns) :This constructor is used to construct a empty Text Field with given number of columns.
JTextField(String text): This constructor is used to construct a Text field initialized with specific text.
JTextField(String text, int columns): This constructor is used to construct a Text field initialized with specific text and columns.
JTextField Methods
Some of Commonly useable methods are listed below.
void addActionListener(ActionListener l): This method is used to adds the specific action listener to receive action events from Text Field.
int getColumns(): This method is used to get number of columns of particular Text Field and return type is Integer.
Action getAction():This method is used to returns currently set Action .
int getHorizontalAlignement(): This method return integer value of horizontal alignment of the text.
void setFont(Font f): This method is used to sets the current font.
void setHorizontalAlignment(int aligment):This method is used to sets the horizontal alignment of text.
void removeActionListener(ActionListener listener): With the help of this method we can remove any specific listener so that text field Is no longer to receives any specific action events.
Example :-
Let’s do coding for Text Field, With the help of below program you can simply get understand about JTextField.
W3AddASwing.java
Create a class and put down below code into the class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
package w3addaswing; import javax.swing.JFrame; import javax.swing.JTextField; public class W3ADDASwing { public static void main(String[] args) { // TODO code application logic here JFrame frame = new JFrame("JTextField Example W3ADDA"); JTextField textfield; textfield = new JTextField("Text Field W3Adda Tutorial"); textfield.setBounds(50, 150, 200, 30); frame.add(textfield); frame.setSize(400, 400); frame.setLayout(null); frame.setVisible(true); } } |
Output :-
Output of this code will look like below image.
This was simple article to get understand about JTextField. I Hope from this article you got clear idea about JTextField.