A text field in Java Swing is a graphical user interface component that allows users to enter text. Swing offers the JTextField
class, a subclass of JComponent
, to construct and manage text fields. Let’s look at different ways to use text fields in a Swing application.
JTextField
library importThe JTextField
utility is part of the Java Swing library. To import JTextField
we can write the following:
import javax.swing.JTextField
JTextField
classTo generate text fields with varying starting attributes, the JTextField
class offers a variety of constructors. The most popular builders are listed below:
JTextField()
: This constructor generates a text field that contains no initial text or icon.
JTextField(String text)
: This constructor produces a text field with the starting text.
JTextField(String text, int columns)
: This constructor generates a text field with the provided beginning text and the requested number of visible columns (width), where the columns
parameter refers to the number of characters that the text field can display horizontally.
JTextField
classLet’s explore some commonly used methods of the JTextField
class that enable us to interact with text fields:
setText(String text)
: This method sets the text displayed in the text field to the specified value.
getText()
: This method retrieves the current text entered by the user in the text field.
setColumns(int columns)
: This method sets the text field’s preferred number of columns (width).
addActionListener(ActionListener listener)
: This method adds an ActionListener
to the text field. The listener will be notified when the user presses the “Enter” key, often indicating the completion of user input.
Let’s create a simple Swing application that demonstrates working with a text field and a button. In this example, the user enters text into a text field, and when the “Set Text” button is clicked, the entered text is updated in all the other text fields.
import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Main { public static void main(String[] args) { SwingUtilities.invokeLater(() -> { createAndShowGUI(); }); } private static void createAndShowGUI() { JFrame frame = new JFrame("Text Fields Example"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setPreferredSize(new Dimension(600, 400)); JPanel panel = new JPanel(new GridBagLayout()); GridBagConstraints constraints = new GridBagConstraints(); constraints.gridx = 0; constraints.gridy = 0; constraints.insets = new Insets(10, 10, 10, 10); JTextField textField1 = new JTextField(); JTextField textField2 = new JTextField("Initial Text"); JTextField textField3 = new JTextField("Initial text with width", 20); textField1.setColumns(20); textField2.setColumns(20); textField3.setColumns(20); constraints.gridy++; panel.add(new JLabel("Text Field 1:"), constraints); constraints.gridy++; panel.add(textField1, constraints); constraints.gridy++; panel.add(new JLabel("Text Field 2:"), constraints); constraints.gridy++; panel.add(textField2, constraints); constraints.gridy++; panel.add(new JLabel("Text Field 3:"), constraints); constraints.gridy++; panel.add(textField3, constraints); ActionListener listener = e -> { JTextField source = (JTextField) e.getSource(); JOptionPane.showMessageDialog(null, "Text entered: " + source.getText()); }; textField1.addActionListener(listener); textField2.addActionListener(listener); textField3.addActionListener(listener); JButton setTextButton = new JButton("Set Text"); setTextButton.setPreferredSize(new Dimension(150, 30)); constraints.gridy++; constraints.gridwidth = 2; constraints.fill = GridBagConstraints.HORIZONTAL; panel.add(setTextButton, constraints); setTextButton.addActionListener(e -> { textField2.setText(textField1.getText()); textField3.setText(textField1.getText()); }); frame.setContentPane(panel); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
We have used the
JFrame
utility to render our text fields in the GUI. It provides a windowed container for creating GUI applications. Refer to the official documentation of JFrame to learn more about it.
The output of the code above will look like this initially:
Enter some text in “Text Field 1:” and press the “Set Text” button. You’ll see the results updating in all the text fields, i.e., the value of the other two text fields will be changed to the value we entered.
Lines 1–4: The code starts by importing essential packages javax.swing
and java.awt
for creating GUIs and handling essential AWT functions.
Lines 7–11: The main
method is the program’s starting point.
Line 8: SwingUtilities.invokeLater
ensures that the GUI components are constructed and shown on the Event Dispatch Thread (EDT) for proper handling.
Line 13: The createAndShowGUI
method establishes Swing GUI components and interactions, encapsulating the application’s core logic.
Lines 14–16: The JFrame
is the application’s main window. A new JFrame
, titled “Text Fields Example,” is created to present the user interface. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)
defines how the application behaves when the user closes the window. setPreferredSize(new Dimension(600, 400))
sets the frame’s preferred size to x pixels, shaping its appearance.
Lines 18–22: A JPanel
called panel
is crafted using GridBagLayout
for flexible grid arrangement. GridBagConstraints
configure component alignment in the grid, while gridx
and gridy
set the starting cell, whereas Insets
provide external padding for components.
Lines 32–45: The provided lines introduce labels and text fields to the panel
utilizing GridBagConstraints
. The command constraints.gridy++
advances the grid row for subsequent components. Employing panel.add(new JLabel("Text Field 1:"), constraints)
, a label is appended for “Text Field 1.” The subsequent line panel.add(textField1, constraints)
incorporates textField1
within the same row. This pattern is replicated for textField2
and textField3
placements.
Lines 47–50: An ActionListener
named listener
responds to Enter key presses by retrieving the source text field and displaying the entered text in a message dialog.
Lines 52–54: The listener is subsequently applied to each text field using addActionListener(listener)
.
Lines 56–61: A JButton
named setTextButton is generated, featuring the label "Set Text" To determine the button’s size, setTextButton.setPreferredSize(new Dimension(150, 30))
is invoked. Simultaneously, constraints.gridy++
facilitates the shift to the succeeding row, while constraints.gridwidth = 2
enables the button’s expansion across two columns. By utilizing constraints.fill = GridBagConstraints.HORIZONTAL
, the button attains a horizontal stretching effect. This refined button is subsequently incorporated into the panel
.
Lines 68–71: The content pane is designated within the frame to finalize the layout. The frame’s dimensions are optimized via frame.pack()
, and its placement at the screen’s center is ensured with frame.setLocationRelativeTo(null)
.
Let’s take a moment to make sure you have correctly understood how to use the JTextField
. The quiz below helps you check if you have understood the concepts.
JTextfield in Swing
Which text field constructor is used to initialize a text field using the initial text?
JTextField()
JTextField(String text)
JTextField(String text, int columns)
JTextField(String text1, String text2)
Free Resources