swing

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. JFormattedTextFieldJPasswordField  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:

ConstructorParameter DetailsDescription
JTextField()NoneCreates 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:

MethodsDescription
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.

JTextArea component is added to the left pane of the JSplitPane component

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.

Three text fields are placed in the highlighted section to accept name

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.

JTextField control to contain full name is followed by a button

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.

Text boxes to accept address are placed in the row

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.

Contact information text boxes are placed in the row

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

Button to generate full details is shown highlighted

5. Description of JTextBox features in the source code

SwingJTextFieldExampleFrame.java

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 component firstName is created with column size 15. KeyListener is added to the field by passing object of KeyAdapter. The background color of firstName field is set to yellow. The KeyListener 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 component fullName 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 component phoneNo 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. Similary JTextField 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.

Download
You can download the full source code of this example here: JTextField Example

Koushik Sanyal

Koushik Sanyal is a resident of a small town Uttarpara, in the suburbs of Kolkata (erstwhile Calcutta) which is one of the biggest cities in India and capital of the state of ‘West Bengal’. He completed Diploma in Information Technology from DoEACC Society (Currently NIELIT), a government of India run autonomous society dedicated for pertaining training in Information Technology. He has spent more than 11 years in IT professional domain as Trainer, Software Developer and Senior Software Developer. Currently he's working as a ‘Senior Software Developer’ in java domain at ‘Greenfield Software Pvt. Ltd in Kolkata, India.
Subscribe
Notify of
guest

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

0 Comments
Inline Feedbacks
View all comments
Back to top button