JTextField basic tutorial and examples

JTextField basic tutorial and examples

JTextField

is a fundamental Swing’s component that allows users editing a single line of text. This article lists common practices when using

JTextField

in Swing development.Table of content:

 

1. Creating a JTextField object

When creating a text field component, it’s common to specify some initial text and/or a number of columns from which the field’s width is calculated.

  • Create a text field with some initial text:
    JTextField textField = new JTextField("This is a text");

    Image: text field with initial text 

  • Create a text field with a specified number of columns:
    JTextField textField = new JTextField(20);

    Image: text field with specified width
     

  • Create a text field with both initial text and number of columns:
    JTextField textField = new JTextField("This is a text", 20);

    Image: text field with initial text and specified width
     

  • Create a default and empty text field then set the text and the number of columns later:
JTextField textField = new JTextField();
textField.setText("This is a text");
textField.setColumns(20);

 

NOTE:

    • If the initial text is not specified, its default value is null (the text field is empty).
    • If the number of columns is not specified, its default value is 0 (then the text field’s width is calculated based on the initial text).
       

2. Adding the  text field to a container

  • A

    JTextField

    can be added to any container like JFrame, JPanel,

    JDialog

    or

    JApplet

    :

    frame.add(textField);
    dialog.add(textField);
    panel.add(textField);
    applet.getContentPane().add(textField);

     

  • Add a

    JTextField

    to the container with a specific layout manager:

frame.add(textField, BorderLayout.CENTER);
panel.add(textField, gridbagConstraints);

  

3. Getting or setting content of the text field

  • Getting all content:
    String content = textField.getText();
  • Getting a portion of the content:
    int offset = 5;
    int length = 10;
    
    try {
    	content = textField.getText(offset, length);
    } catch (BadLocationException ex) {
    	// invalid offset/length
    }

     That will return 10 characters from position 5th in the text.

  • Setting content:
textField.setText("another text");

 

4. Setting tooltip text for JTextField

Set tooltip for the text field as follows:

textField.setToolTipText("Please enter some text here");

 Image:set tooltip for text fieldWe can also set HTML for the tooltip text:

textField.setToolTipText("<html><b><font color=red>"
					+ "Please enter some text here" + "</font></b></html>");

 Image:html tooltip text field

5. Setting input focus for JTextField

is a fundamental Swing’s component that allows users editing a single line of text. This article lists common practices when usingin Swing development.When creating a text field component, it’s common to specify some initial text and/or a number of columns from which the field’s width is calculated.Set tooltip for the text field as follows:Image:We can also set HTML for the tooltip text:Image:

Normally, the text field gets focused when the user is clicking on it or pressing the TAB key. To set input focus programmatically, use the following code:

  • Setting input focus initially just after the container (such as a

    JFrame

    ) is displayed:

    frame.setVisible(true);
    textField.requestFocusInWindow();

     

  • Setting input focus at any time: It’s recommend to request the focus inside a

    SwingUtilities.invokeLater()

    call:

SwingUtilities.invokeLater(new Runnable() {
	@Override
	public void run() {
		textField.requestFocusInWindow();
	}
});

 

6. Adding event listeners for JTextField

  • We can capture the event in which the user hits Enter key while typing in the text field. For example:
    textField.addActionListener(new ActionListener() {
    	@Override
    	public void actionPerformed(ActionEvent event) {
    		System.out.println("The entered text is: " + textField.getText());
    	}
    });

     

  • Capture key events which happen while the user is typing into the text field:
textField.addKeyListener(new KeyListener() {

	@Override
	public void keyTyped(KeyEvent event) {
		System.out.println("key typed");
	}

	@Override
	public void keyReleased(KeyEvent event) {
		System.out.println("key released");
	}

	@Override
	public void keyPressed(KeyEvent event) {
		System.out.println("key pressed");
	}
});

 

The order of key events is key pressed, key typed and key released. We can use this technique to validate field’s content on-the-fly. In the following example, we check the field’s content whenever the user is typing. If the content is empty, disable the action button; otherwise enable the button:

textField.addKeyListener(new KeyAdapter() {
	public void keyReleased(KeyEvent event) {

		String content = textField.getText();
		if (!content.equals("")) {
			button.setEnabled(true);
		} else {
			button.setEnabled(false);
		}
	}
});

NOTE

: In this case, we use the

KeyAdapter

class which implements the

KeyListener

interface, so we have to override only the method we want.

 

 

7. Working with text selection in JTextField

: In this case, we use theclass which implements theinterface, so we have to override only the method we want.

We can programmatically select the text field’s content.

  • Select all text:
    textField.selectAll();

    Image: select all text field content 

  • Select only a portion of text:
    textField.setSelectionStart(8);
    textField.setSelectionEnd(12);

    Image: select a portion of text field content 

  • Set color for the selection and the selected text:
    textField.setSelectionColor(Color.YELLOW);
    textField.setSelectedTextColor(Color.RED);

    Image: set selected color text field 

  • Set position of the caret and its color:
textField.setCaretColor(Color.RED);
textField.setCaretPosition(10);

Image: customize caret in text field 

8. Customizing JTextField’s appearance

  • Disable editing the field’s content:
    textField.setEditable(false);

    Image: disabled field
     

  • Set horizontal alignment of text:
    textField.setHorizontalAlignment(JTextField.CENTER);

    Image: centered alignment text field
    Valid values for the method

    setHorizontalAlignment()

    are:

    JTextField.LEFT
    JTextField.CENTER
    JTextField.RIGHT
    JTextField.LEADING
    JTextField.TRAILING

     

  • Set font style, background color and foreground color:
textField.setFont(new java.awt.Font("Arial", Font.ITALIC | Font.BOLD, 12));
textField.setForeground(Color.BLUE);
textField.setBackground(Color.YELLOW);

Image: colorful text field 

9. JTextField demo program

Image:Image:

For your reference and testing purpose, we created a simple demo program looks like this:

JTextField demo program

When you are typing something in the text field and hit Enter, the following message dialog appears:

message dialog 1

If the field is empty, the OK button is disabled:

button disabled

And when clicking the button:

message dialog 2

You can download, run and view source code of this program in the attachment section.

 

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

Attachments:Download this file (SwingJTextFieldDemo.zip)SwingJTextFieldDemo.zip[Source code and runnable jar file]11 kB

Add comment