Working with Text Fields in Java

Working with Text Fields in Java

JTextField is a class in Swing that allows users to create text fields of varying sizes and types. The JTextField lass is available in the javax.swing package. If you want to use this widget or component, you will need to do the following import:

import javax.swing.*;

The text box that is produced using the JTextField class can be edited as many times as required. The JTextField inherits the JTextComponent class. There are several ways in which you can initialize a JTextFiel. Some of the constructors are as follows:

  • JTextField(): This will just create a new text field with default width and height.
  • JTextField(int columns): This text field will have a specified number of columns as given in the parameter.
  • JTextField(String text): The text field will be created with an editable text. For example: “Enter your password” in a password TextBox.
  • JTextField(String text, int columns): This text box will have the mentioned number of columns as well as a default text.
  • JTextField(Document doc, String text, int columns): Along with the columns and a default text, the document where the text will be stored is also fed in as a parameter.

Some of the Methods JTextField are

  • setColumns(int n): Setting a specific number of columns to the text field.
  • setFont(Font f): Choosing the font of field.
  • addActionListener(ActionListener I): To set an action to the field like a button.
  • int getColumns(): to get the number of columns in a JTextField.


import java.awt.event.*;
import java.swing.*;
class text extends JFrame implements ActionListener {
static JTextField t;
static JFrame f;
static JButton b;
static JLabel l;

public static void main (String args [])
f = new JFrame(“textfield”);
l = new JLabel(“Enter something here”);
b = new JButton(“Enter”);
text te = new text();
t = new JTextField(16);
JPanel p = new JPanel();

public void actionPerformed(ActionEvent e)
String str = e.getActionCommand();
t.setText(“ “);



  • Barry Allen

    A Full Stack Developer with 10+ years of experience in different domain including SAP, Blockchain, AI and Web Development.

    View all posts


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.