Create new JTextField

In this example we are going to see how to create a new JTextField component in a Java Desktop Application. Text fields in general are one of the most common ways for you application to get user input. Using text fields you give the user the ability to provide text input to your app.

It’s very easy to create a new JTextField as all you have to do is:

  • Create a class that extends JFrame.
  • Create a new JTextField.
  • Use setText to write some text to the text field.
  • Use new JTextField("Some text") to initialize the text field with some text.
  • Use new JTextField(10) to set the default columns of the text field.
  • Use new JTextField("some text", 3) to specify the above properties at once.
  • Use add to add the text fields to the frame.

Let’s take a look at the code:

package com.javacodegeeks.snippets.desktop;

import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JTextField;

public class CreateNewJTextField extends JFrame {

	private static final long serialVersionUID = 1L;

	public CreateNewJTextField() {

		// set flow layout for the frame
		this.getContentPane().setLayout(new FlowLayout());

		// create empty JTextField
		JTextField field1 = new JTextField();
		field1.setText("Java Code Geeks");

		// create JTextField with default text
		JTextField field2 = new JTextField("Java Code Geeks");

		// create JTextField with specified number of columns
		JTextField field3 = new JTextField(10);

		// create JTextField with default text and columns
		JTextField field4 = new JTextField("Java Code Geeks", 10);

		// add textfields to frame


	private static void createAndShowGUI() {

  //Create and set up the window.

  JFrame frame = new CreateNewJTextField();

  //Display the window.





	public static void main(String[] args) {

  //Schedule a job for the event-dispatching thread:

  //creating and showing this application's GUI.

  javax.swing.SwingUtilities.invokeLater(new Runnable() {

public void run() {





This was an example on how to create a new JTextField in a Java Desktop Application.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Notify of

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

Inline Feedbacks
View all comments
Back to top button