A Textfield is a component used for displaying, inputting and editing a single line of plain text. We can create text field by creating an instance of JTextField class. The JTextComponent is a superclass of JTextField that provides common set of methods used by JTextfield.
The following table shows some methods of this class:
Method | Description |
JTextField() | Constructs anew textfield |
JTextField(int) | Constructsa textfield withthe number of columns(size) entered |
JTextField(String) | Constructsa textfield with the specified text |
setText(String) | Sets the textof the textfield to the given |
getText() | Returns the text of the textfield
|
setEnabled(boolean) | Sets whetherthe textfield is enabled(true) or disabled(false) |
import javax.swing.*;
import java.awt.*;
class JTextFieldExample extends JFrame
{
JTextFieldExample()
{
setLayout(new FlowLayout());
JLabel lblRollno = new JLabel("Rollno : ");
JTextField txtRollno = new JTextField(15);
JLabel lblName = new JLabel("Name :");
JTextField txtName = new JTextField("Mr Thakur",15);
add(lblRollno); add(txtRollno);
add(lblName); add(txtName);
}
}
class JTextFieldJavaExample
{
public static void main(String args[])
{
JTextFieldExample frame = new JTextFieldExample();
frame.setTitle("JTextField in Java Swing Example");
frame.setBounds(200,250,150,150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}