• 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 textfield or a password field. JTextField is an input component allowing users to add some text. JPasswordField is a special type of textfield that allows you to change the character being displayed to the user.


    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();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.gridwidth = 1;
            gbc.gridheight = 1;
            frame.add(lblUsername, gbc);
            gbc.gridx = 1;
            gbc.gridwidth = 5;
            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);
        public static void main(String args[]) {
            TextFieldTest test = new TextFieldTest();

    when we run our program, the UI will be:

    jlabel jtextfield and jpassword field
    • 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”.

    Next tutorial is about how to use JTextArea in Java.

    Related Post