Java Swing JTextField Example
Swing offers us components through which users can type in text input. JTextField
is one such component which is used to allow applications to accept single line input. Even user can go for standard operations like copy, paste, cut, delete.
1. Introduction
Swing offers several components to ease user experience while typing in text or edit text. Different such are there for use in different scenarios. JTextField
is one such input box, where user can type in or edit single line text. JTextField
belongs to
package javax.swing
. JTextField
extends JTextComponent
and implements SwingConstants
. JTextField
is a lightweight component which allows users to edit single line of text. JFormattedTextField
, JPasswordField
are derived classes of JTextField
. JTextField
has a compatible component java.awt.TextField
. JTextField
has capabilities not available in java.awt.TextField
.
2. Technologies Used
- Java (jdk 1.6.x or higher will be fine)
- Eclipse ( Galileo or higher version is required)
3. API Description
Commonly used Constructors:
Constructor | Parameter Details | Description |
JTextField() | None | Creates a new TextField object. Initial string is set to null. Number of columns is set to 0. |
JTextField(String text) | The text to be displayed or null. | Creates a new TextField object initialized with the specified text. Number of columns is set to 0. |
JTextField(String text, int columns) | The text to be displayed or null.
The number of columns to use to calculate the preferred width. If 0 then width will be the naturally result of component implementation. | Creates a new TextField object initialized with the specified text and columns. |
JTextField(int columns) | The number of columns to use to calculate the preferred width. . If 0 then width will be the naturally result of component implementation. | Creates a new empty TextField object with the specified number of columns. |
Commonly used Methods:
Methods | Description |
void addActionListener(ActionListener l) | It is used to add the specified action listener to receive action events from JTextField component. |
void addKeyListener(KeyAdapter k) | It is used to add the specified key listener to receive key events from this JTextField component. |
void setBackground(Color c) | It is used to set the background color to the JTextField component. |
void getText() | It is used to get the text entered in JTextField component. |
4. Description of JTextBox features in the example
In this example, the frame contains one JSPlitPane
component. On the left side of that component, one JScrollPane
component based on JTextArea
component of size 500 X 600 has been placed.

On the right hand side, We have multiple JTextField
components. One such set of JTextField
refers to accepting First Name, Middle Name, Last Name. Each of these components is of column 15 wide and each of these fields can only accept alphabets and also none of these components can accept name more than 15 characters long. Background color of all those controls are also set to yellow.

Next row contains one JTextField
component of width 60 columns to contain full name and a button. The text field is populated once the button is clicked and the full name is generated by concatenating First Name, Middle Name and Last Name. Also the text field is set to be non-editable. Highlighted portion in the below image depicts those controls.

In the third row, 3 JTextField
controls appear. First one is meant to contain Address line 1. The only restriction imposed to this control is that this field can’t contain text more than 50 characters long. The next field is meant for containing Address line 2. Here also only restriction is imposed by means of text length and the length is 20. The third JTextField
is meant for containing pin code. Naturally to restrictions imposed are like the control can’t contain text of more than 6 characters long and non other that digits will be accepted.

Forth row contains JTextField
controls to accept contact information. The restriction imposed for Cell No is, text length can’t go more than 10 and only digits are allowed. In case of email id, the restriction is text can’t contain more than 30 characters and on focus lost, email is compared with the standard email pattern. In case validation fails, email field is set to empty string.

Last row contains one button, and once the button is clicked JTextArea
control is populated with all text box values composed together.

5. Description of JTextBox features in the source code
SwingJTextFieldExampleFrame.java
001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047 048 049 050 051 052 053 054 055 056 057 058 059 060 061 062 063 064 065 066 067 068 069 070 071 072 073 074 075 076 077 078 079 080 081 082 083 084 085 086 087 088 089 090 091 092 093 094 095 096 097 098 099 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 | package com.javacodegeeks.example.swing.jtextfield; import java.awt.Button; import java.awt.CardLayout; import java.awt.Color; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.SwingUtilities; public class SwingJTextFieldExampleFrame extends JFrame { /** * */ private static final long serialVersionUID = -1927825705131809212L; private String firstName; private String middleName; private String lastName; private String fullName; private String address1; private String address2; private String pin; private String cellNo; private String emailId; public SwingJTextFieldExampleFrame(){ setSize( 500 , 600 ); setTitle( "JTextField Demo" ); JSplitPane splitPane = new JSplitPane(); splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT); splitPane.setDividerLocation( 250 ); final JTextArea textArea = new JTextArea( 40 , 50 ); JScrollPane scrollText = new JScrollPane(textArea); textArea.setEditable( false ); splitPane.setLeftComponent(scrollText); add(splitPane); JPanel panel = new JPanel( new GridLayout( 0 , 1 )); splitPane.setRightComponent(panel); JPanel namePanel = new JPanel( new FlowLayout(FlowLayout.LEFT)); JPanel fullNamePanel = new JPanel( new FlowLayout(FlowLayout.LEFT)); JPanel addressPanel = new JPanel( new FlowLayout(FlowLayout.LEFT)); JPanel contactsPanel = new JPanel( new FlowLayout(FlowLayout.LEFT)); JPanel submitPanel = new JPanel( new FlowLayout(FlowLayout.CENTER)); addNameControls(namePanel,fullNamePanel); addAddressControls(addressPanel); addContactsControls(contactsPanel); JButton submitButton = new JButton( "Generate Contact Details" ); submitButton.addMouseListener( new MouseAdapter(){ public void mouseClicked(MouseEvent evt) { if (SwingUtilities.isLeftMouseButton(evt)){ String fullStr = "Name is:" +getFullName(); fullStr += "\nAddress is: " +getAddress1()+ " " +getAddress2()+ "\nPin is:" +getPin()+ "\nPhone No is: " +getCellNo()+ "\nEmail Id is: " +getEmailId(); textArea.setText(fullStr); } } }); submitPanel.add(submitButton); panel.add(namePanel); panel.add(fullNamePanel); panel.add(addressPanel); panel.add(contactsPanel); panel.add(submitPanel); } private void addNameControls(JPanel namePanel, JPanel fullNamePanel){ JLabel fName = new JLabel( "First name: " ); namePanel.add(fName); final JTextField firstName = new JTextField( 15 ); firstName.setBackground(Color.YELLOW); firstName.addKeyListener( new KeyAdapter() { public void keyTyped(KeyEvent e) { char letter = e.getKeyChar(); if (firstName.getText().length() >= 15 ) e.consume(); else if (!Character.isLetter(letter)){ e.consume(); } } }); firstName.addFocusListener( new FocusListener(){ public void focusGained(FocusEvent fe){ } public void focusLost(FocusEvent fe){ setFirstName(firstName.getText()); } }); namePanel.add(firstName); JLabel mName = new JLabel( "Middle name: " ); namePanel.add(mName); final JTextField middleName = new JTextField( 15 ); middleName.setBackground(Color.YELLOW); namePanel.add(middleName); middleName.addKeyListener( new KeyAdapter() { public void keyTyped(KeyEvent e) { char letter = e.getKeyChar(); if (middleName.getText().length() >= 15 ){ e.consume(); } else if (!Character.isLetter(letter)){ e.consume(); } } }); middleName.addFocusListener( new FocusListener(){ public void focusGained(FocusEvent fe){ } public void focusLost(FocusEvent fe){ setMiddleName(middleName.getText()); } }); JLabel lName = new JLabel( "Last name: " ); namePanel.add(lName); final JTextField lastName = new JTextField( 15 ); lastName.setBackground(Color.YELLOW); lastName.addKeyListener( new KeyAdapter() { public void keyTyped(KeyEvent e) { char letter = e.getKeyChar(); if (middleName.getText().length() >= 15 ){ e.consume(); } else if (!Character.isLetter(letter)){ e.consume(); } } }); lastName.addFocusListener( new FocusListener(){ public void focusGained(FocusEvent fe){ } public void focusLost(FocusEvent fe){ setLastName(lastName.getText()); } }); namePanel.add(lastName); addFullNameControls(fullNamePanel,firstName,middleName,lastName); } private void addFullNameControls(JPanel fullNamePanel, final JTextField firstName, final JTextField middleName, final JTextField lastName){ JLabel fullNameTxt = new JLabel( "Full name: " ); fullNamePanel.add(fullNameTxt); final JTextField fullName = new JTextField( 60 ); fullName.setEditable( false ); fullNamePanel.add(fullName); final Button button = new Button( "Generate Full Name" ); button.addMouseListener( new MouseAdapter(){ public void mouseClicked(MouseEvent evt) { if (SwingUtilities.isLeftMouseButton(evt)){ String fName = firstName.getText(); String mName = middleName.getText(); String lName = lastName.getText(); if (mName.length() > 0 ) fullName.setText(fName+ " " +mName+ " " +lName); else fullName.setText(fName+ " " +lName); setFullName(fName+ " " +mName+ " " +lName); } } }); fullNamePanel.add(button); } private void addAddressControls(JPanel addressPanel){ JLabel address1Lbl = new JLabel( "Address1: " ); addressPanel.add(address1Lbl); final JTextField address1 = new JTextField( 50 ); address1.addFocusListener( new FocusListener(){ public void focusLost(FocusEvent fe){ setAddress1(address1.getText()); } public void focusGained(FocusEvent fe){ } }); address1.addKeyListener( new KeyAdapter() { public void keyTyped(KeyEvent e) { if (address1.getText().length() >= 50 ) e.consume(); } }); addressPanel.add(address1); JLabel addressLb2 = new JLabel( "Address 2: " ); addressPanel.add(addressLb2); final JTextField address2 = new JTextField( 20 ); address2.addFocusListener( new FocusListener(){ public void focusLost(FocusEvent fe){ setAddress2(address2.getText()); } public void focusGained(FocusEvent fe){ } }); address2.addKeyListener( new KeyAdapter() { public void keyTyped(KeyEvent e) { if (address2.getText().length() >= 20 ) e.consume(); } }); addressPanel.add(address2); JLabel addressLb3 = new JLabel( "Pin: " ); addressPanel.add(addressLb3); final JTextField pin = new JTextField( 6 ); pin.addFocusListener( new FocusListener(){ public void focusLost(FocusEvent fe){ setPin(pin.getText()); } public void focusGained(FocusEvent fe){ } }); pin.addKeyListener( new KeyAdapter() { public void keyTyped(KeyEvent e) { char letter = e.getKeyChar(); if (pin.getText().length() >= 15 ){ e.consume(); } else if (!Character.isDigit(letter)){ e.consume(); } } }); addressPanel.add(pin); } private void addContactsControls(JPanel contactPanel){ JLabel phone = new JLabel( "Cell No: " ); contactPanel.add(phone); final JTextField phoneNo = new JTextField( 10 ); phoneNo.addFocusListener( new FocusListener(){ public void focusLost(FocusEvent fe){ setCellNo(phoneNo.getText()); } public void focusGained(FocusEvent fe){ } }); phoneNo.addKeyListener( new KeyAdapter() { public void keyTyped(KeyEvent e) { char letter = e.getKeyChar(); if (phoneNo.getText().length() >= 10 ) e.consume(); else if (!Character.isDigit(letter)){ e.consume(); } } }); contactPanel.add(phoneNo); JLabel email = new JLabel( "Email Id: " ); contactPanel.add(email); final JTextField emailId = new JTextField( 30 ); emailId.addFocusListener( new FocusListener(){ public void focusLost(FocusEvent fe){ String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$" ; Pattern pat = Pattern.compile(ePattern); Matcher match = pat.matcher(emailId.getText()); if (!match.matches()){ JOptionPane.showMessageDialog(emailId, "Wrong email id format." ); emailId.setText( "" ); } setEmailId(emailId.getText()); } public void focusGained(FocusEvent fe){ } }); contactPanel.add(emailId); emailId.addKeyListener( new KeyAdapter() { public void keyTyped(KeyEvent e) { if (emailId.getText().length() >= 30 ){ e.consume(); } } }); contactPanel.add(emailId); } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this .firstName = firstName; } public String getMiddleName() { return middleName; } public void setMiddleName(String middleName) { this .middleName = middleName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this .lastName = lastName; } public String getAddress1() { return address1; } public void setAddress1(String address1) { this .address1 = address1; } public String getAddress2() { return address2; } public void setAddress2(String address2) { this .address2 = address2; } public String getPin() { return pin; } public void setPin(String pin) { this .pin = pin; } public String getCellNo() { return cellNo; } public void setCellNo(String cellNo) { this .cellNo = cellNo; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this .emailId = emailId; } public String getFullName() { return fullName; } public void setFullName(String fullName) { this .fullName = fullName; } } |
- line 99 – 123: The
JTextField
componentfirstName
is created with column size 15.KeyListener
is added to the field by passing object ofKeyAdapter
. The background color offirstName
field is set to yellow. TheKeyListener
is used to check if only alphabets are inserted in the fields and text size doesn’t exceed 15. Also focus attribute is added to the firstName box. Once focus is lost for firstName text box,firstName
attribute of the class is set to value of the firstName text box. - line 189 – 208: The
JTextField
componentfullName
is created with column size 60. The fullName field is set as non-editable.MouseListener
is added to the button so that if left mouse button is clicked fullName text box will be populated with first name, middle name and last name in order. - line 293 – 338: The
JTextField
componentphoneNo
is created with column size 10.KeyListener
is added to the phoneNo text box so as to ensure that none other than digits are inserted into the text box and entered text size doesn’t exceed 10 characters. However restriction is only applicable in case characters are typed in. For paste operation we need to add other checks. SimilaryJTextField
component of emailId of size 30 columns is also added.FocusListener
is added to it so that at the time focus is taken out of emailId field, entered emailId can be validated.
6. Summary
In this example common operations of JTextField
are addressed. For further reading links shared in this article can be referred.
7. Download the Source Code
This was an example of Java JTextField
.
You can download the full source code of this example here: JTextField Example