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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
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:

  • 1
    tfUsername = new JTextField(20);

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

  • 1
    pfPassword = new JPasswordField(20);

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

  • 1
    lblUsername = new JLabel("Username");

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

  • 1
    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!