Java Graphical User Interface(GUI): JTextField and JPasswordField functions Using Eclipse IDE

What Will I Learn?

  • The user will learn the concept of JTextField and JPasswordField.
  • The user will learn how JTextField is imported and put in a JFrame container.
  • The user will also learn how to combine JLabel, JTextField and JPasswordField in a container.

Requirements

  • A computer System is required for this tutorial.
  • Java Software Development Kit(JDK) must be installed on your computer.
  • An Integrated Development Environment(IDE) such as Eclipse or NetBeans is required to be installed on your computer.

Get JDK here

Get Eclipse here

Get NetBeans here

Difficulty

Learning programming codes takes time and patience. This program imports and makes use of inbuilt methods that may require going through in order to memorize. I would rate the difficulty level as Intermediate.

Tutorial Contents

JTEXTFIELD

The JTextField Component allows the user to display and edit a single line of text. The user can also add functionalities to the text such as BOLD, ITALIC, and ***COLOR.

Wideskills

This tutorial will center on creating the TextField Component and typing words in the field.

JPASSWORDFIELD

The JPasswordField class, a subclass of JTextField, provides specialized text fields for password entry. For security reasons, a password field does not show the characters that the user types. Instead, the field displays a character different from the one typed, such as an asterisk '*'. As another security precaution, a password field stores its value as an array of characters, rather than as a string.

Oracle

This tutorial picks up from the last tutorial where JLabel was introduced. The program uses JLabel to display a line of text to the screen and then uses JTextField and JPasswordField to create space where the user can enter texts. The JTextField and JPasswordField Components are the displayed on the screen.

1.png

2.png

CODE BLOCK

TEXTFIELD CLASS
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
public class textField extends JFrame {
    private JLabel text;
    private JTextField field;
    private JPasswordField password;
    public textField() {
        super("JTextField Demo");
        setLayout(new FlowLayout());
        text = new JLabel("Enter Username and Password");
        text.setToolTipText("Login Details");
        add(text);
        field = new JTextField("Username", 15 );
        add(field);
        password = new JPasswordField("Password", 15);
        add(password);
    }
}
MAIN CLASS
import javax.swing.JFrame;
public class Main {
    public static void main (String args []) {
    textField textObject = new textField();
    textObject.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    textObject.setSize(350,150);
    textObject.setVisible(true);
    }
}

TEXTFIELD CLASS

import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPasswordField;

These are Import Statements. Import Statements are used to reference methods that are in other packages. Java comes with a bunch of in built methods and these methods are in different packages. When the user imports a class, the user has access to all methods in the class because they are automatically imported.

public class textField extends JFrame {

This is the name of the current class. When you start a new class, it must be saved with a name. This class extends JFrame. In Java, it is possible for classes to inherit properties of another class. Here, this class inherits basic Frame properties like a window with close, maximize and minimize buttons from the JFrame class. The extends keyword is used to achieve this.

private JLabel text;

A variable declaration of JLabel type. The private keyword is used here, this means that this variable can only be accessed from within this class and not from other classes.

Public keyword is used if the user wants the variable to be accessed from anywhere.

private JTextField field;

This is also a variable declaration of JTextField type. As the first variable, The private keyword is used here, meaning it is only visible from inside this class. This variable is the object that will hold the text that will be inputted in the text field.

private JPasswordField password;

A variable declaration of JPasswordField type. The object password will hold the text that will be entered in the password field.
Public keyword is used if the user wants the variable to be accessed from anywhere.

public textField() (

A Constructor is a block of code that lets you initialize variables immediately an object is created. Methods can be created and called later but with constructors, initialization is done immediately. Constructors have the same name as the class name and is called when an object of the class in created.

The above constructor does not carry any arguments and is created to hold the JTextField and JPasswordField components.

super(JTextField Demo);

The super keyword is used here to refer to properties of a superclass; in this case the JFrame class.

In this context, it is used to set the title of the newly created window. The title of the window is “JTextField Demo”

setLayout(new FlowLayout());

The FlowLayout class was imported earlier. This provides a basic layout that is used by JFrame components.

The FlowLayout class puts components in a row, sized at their preferred size. If the horizontal space in the container is too small to put all the components in one row, the FlowLayout class uses multiple rows.

Source

text = new JLabel(Enter Username and Password)

JLabel Component, displays unselectable text and images. If you need to create a component that displays a string, an image, or both, you can do so by using or extending JLabel. If the component is interactive and has a certain state, use a button instead of a label.

oracle

Here, JLabel is used to set the text that will appear on the screen and assign it to the JLabel variable text.

text.setToolTipText();

An additional functionality is added to the JLabel object. It performs the same function as it did in the last tutorial. The .setToolTipText method is called using the JLabel variable and a dot(.) separator.
This displays a String message when the mouse is hovered over the JLabel text.

add(text)

Now that the window is created, the keyword add[] is used to add the JLabel component to the container so it will be visible to the user.

field = new JTextField(, 15);

Here, the user is allowed to enter a single line of text. The user can edit the text if the user wishes. The newly entered text is then assigned to the object field. The maximum number of characters allowed for this text is 15.

add(text)

The component is added to the screen using the add[] keyword.

password = new JPasswordField(, 15);

The user enters texts here but it will be registered as asterisk. The main characters the user enters will not be visible because this is a password field. The user can also edit the text if the user wishes. The newly entered text is then assigned to the object password. Maximum number of characters allowed is 15.

add(text)

The component is added to the screen using the add[] keyword.

MAIN CLASS

Import javax.swing.JFrame;

This is an import statement. This statement is used specifically to import the JFrame class from Application Program Interface (API). This allows the user to use all methods contained in it.

public class Main {

This is just like creating a new file or document and saving it with a name. This is the name of the new class created.

textField textObject = new textField();

An Object of the textField class is created. This enables the user to call in built GUI methods that will help to properly display the JTextField and JPassword component to the screen.

Object.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

This inbuilt method needs to be called before the program is run . This method states the default behavior of the windows when the “close”(x) button is clicked.
Here, it tells the window to close.

Object.setSize(350,150);

This is to set the size of the object to the specified width and height. In this case, the specified dimensions are (350,150).

Values of width and height are non-negative integers. The constructors that allow you to create a dimension do not prevent you from setting a negative value for these properties. If the value of width or height is negative, the behavior of some methods defined by other objects is undefined.

Oracle

Object.setVisible(true);

This simply determines whether a component is displayed on the screen. It has two states. True and false.

With setVisible( false ), if the Component is not already marked invisible, setVisible calls invalidate() which invalidates the Container’s layout and the chain of parents since there is now more screen real estate in the Container and the positions of the siblings must be adjusted to flow into the freed space.

With setVisible( true ), if the Component is not already marked visible,setVisible calls invalidate() which invalidates the Container’s layout and the chain of parents since there is now less screen real estate in the Container and the positions of the siblings must be adjusted to squeeze in this new Component.

mindprod

3.png

4.png

When the program is run, The JFrame Component contains the JTextField and JPasswordField Components. The JTextField has "username" entered by default, the user may now delete it and enter username. JPasswordField is also has "password" by default but user can also erase and enter password.

5.png

6.png

Source Codes from GitHub Account.

NOTE

All Swing Components whose names begin with "J" descend from the JComponent class e;g JTextField, JLabel, JPasswordField and are all different concepts. However, similar codes is used to implement it in a JFrame container. This makes them easier to understand.

Also, JTextField and JPasswordField Components usually continue with an Event Handler. An Event Handler tells the program what to do if the user clicks "OK" or hits "Enter".

This will be the subject of the next tutorial.

You can get the codes here if you want to try it on your own.

Curriculum

Similar posts already posted on Utopian are:



Posted on Utopian.io - Rewarding Open Source Contributors

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center