How to use JLabel, JTextField, and JPasswordField in Java

JLabel is a component used for displaying a label for some components. It is commonly partnered with a text field or a password field. JTextField is an input component allowing users to add some text. JPasswordField in Java is a special type of text field that allows you to hide or change the character being displayed to the user.

JLabel, JTextField, and JPasswordField in Java Example

package com.javapointers.javase;

import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class TextFieldTest {

    JTextField tfUsername;
    JPasswordField pfPassword;
    JLabel lblUsername, lblPassword;
    GridBagLayout gbl;
    GridBagConstraints gbc;

    public TextFieldTest() {
        tfUsername = new JTextField(20);
        pfPassword = new JPasswordField(20);


        lblUsername = new JLabel("Username");
        lblPassword = new JLabel("Password");

        gbl = new GridBagLayout();
        gbc = new GridBagConstraints();

        JFrame frame = new JFrame();
        frame.setLayout(gbl);

        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 1;
        gbc.gridheight = 1;
        frame.add(lblUsername, gbc);

        gbc.gridx = 1;
        gbc.gridwidth = 5;
        gbc.weightx=1;
        frame.add(tfUsername, gbc);

        gbc.gridy = 1;
        gbc.gridx = 0;
        gbc.gridwidth = 1;
        frame.add(lblPassword, gbc);

        gbc.gridx = 1;
        gbc.gridwidth = 5;
        frame.add(pfPassword, gbc);

        frame.pack();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String args[]) {
        TextFieldTest test = new TextFieldTest();
    }
}

when we run our program, the UI will be:

  • tfUsername = new JTextField(20);

means to create a new instance of JTextField with an initial width of 20.

  • pfPassword = new JPasswordField(20);

create a new instants of JPasswordField with an initial width of 20.

  • lblUsername = new JLabel("Username");

create a new instance of JLabel that will display the string “Username”.

  • lblPassword = new JLabel("Password");

create a new instance of JLabel that will display the string “Password”.

The next tutorial is about how to use JTextArea in Java.

Share this tutorial!