In this tutorial

You will learn how to...
  • How to add a JTextField.
  • How to get information from the JTextField.
  • How to enable and disable a widget.
  • How to create a JPasswordField.
  • To understand differences between both.
  • To use the MVC pattern to restrict text going into a JTextField.

JTextField - Part 1

JTextFields are a very useful part of your Swing Toolkit. Simply put, the TextField lets the user enter text into your program without using a command line prompt.

This tutorial will start by quickly showing how to display a JTextfield. Then, we shall look at more specialised forms of TextFields...JPasswordFields and a personalised form of JTextField that lets you restrict the number of characters in the box.

We shall have to use a new example, our scoreboard example is not very useful for showing a JTextField. This time we will have a go at a basic login screen. The login screen is made of various labels, two JTextFields and a JButton. The username for this login is "Bob" and the password is "Robert".

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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
import javax.swing.*;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class TextFieldExample implements  ActionListener{

    JPanel textPanel, panelForTextFields, completionPanel;
    JLabel titleLabel, usernameLabel, passwordLabel, userLabel, passLabel;
    JTextField usernameField, loginField;
    JButton loginButton;

    public JPanel createContentPane (){

        // We create a bottom JPanel to place everything on.
        JPanel totalGUI = new JPanel();
        totalGUI.setLayout(null);

        titleLabel = new JLabel("Login Screen");
        titleLabel.setLocation(0,0);
        titleLabel.setSize(290, 30);
        titleLabel.setHorizontalAlignment(0);
        totalGUI.add(titleLabel);

        // Creation of a Panel to contain the JLabels
        textPanel = new JPanel();
        textPanel.setLayout(null);
        textPanel.setLocation(10, 35);
        textPanel.setSize(70, 80);
        totalGUI.add(textPanel);

        // Username Label
        usernameLabel = new JLabel("Username");
        usernameLabel.setLocation(0, 0);
        usernameLabel.setSize(70, 40);
        usernameLabel.setHorizontalAlignment(4);
        textPanel.add(usernameLabel);

        // Login Label
        passwordLabel = new JLabel("Password");
        passwordLabel.setLocation(0, 40);
        passwordLabel.setSize(70, 40);
        passwordLabel.setHorizontalAlignment(4);
        textPanel.add(passwordLabel);

        // TextFields Panel Container
        panelForTextFields = new JPanel();
        panelForTextFields.setLayout(null);
        panelForTextFields.setLocation(110, 40);
        panelForTextFields.setSize(100, 70);
        totalGUI.add(panelForTextFields);

        // Username Textfield
        usernameField = new JTextField(8);
        usernameField.setLocation(0, 0);
        usernameField.setSize(100, 30);
        panelForTextFields.add(usernameField);

        // Login Textfield
        loginField = new JTextField(8);
        loginField.setLocation(0, 40);
        loginField.setSize(100, 30);
        panelForTextFields.add(loginField);

        // Creation of a Panel to contain the completion JLabels
        completionPanel = new JPanel();
        completionPanel.setLayout(null);
        completionPanel.setLocation(240, 35);
        completionPanel.setSize(70, 80);
        totalGUI.add(completionPanel);

        // Username Label
        userLabel = new JLabel("Wrong");
        userLabel.setForeground(Color.red);
        userLabel.setLocation(0, 0);
        userLabel.setSize(70, 40);
        completionPanel.add(userLabel);

        // Login Label
        passLabel = new JLabel("Wrong");
        passLabel.setForeground(Color.red);
        passLabel.setLocation(0, 40);
        passLabel.setSize(70, 40);
        completionPanel.add(passLabel);

        // Button for Logging in
        loginButton = new JButton("Login");
        loginButton.setLocation(130, 120);
        loginButton.setSize(80, 30);
        loginButton.addActionListener(this);
        totalGUI.add(loginButton);

        totalGUI.setOpaque(true);    
        return totalGUI;
    }

    // With this action performed, we simply check to see if the username and 
    // password match "Bob" as the username and "Robert" as the password.
    // If they do, we set the labels ajacent to them to "Correct!" and color
    // them green.
    // At the end, we check if both labels are green. If they are, we set the
    // screen to be 'Logging In'.

    public void actionPerformed(ActionEvent e) {

        if(e.getSource() == loginButton)
        {
            if(usernameField.getText().trim().compareTo("Bob") == 0)
            {
                userLabel.setForeground(Color.green);
                userLabel.setText("Correct!");
            }
            else
            {
                userLabel.setForeground(Color.red);
                userLabel.setText("Wrong!");
            }

            if(loginField.getText().trim().compareTo("Robert") == 0)
            {
                passLabel.setForeground(Color.green);
                passLabel.setText("Correct!");
            }
            else
            {
                passLabel.setForeground(Color.red);
                passLabel.setText("Wrong!");
            }

            if((userLabel.getForeground() == Color.green) 
			&& (passLabel.getForeground() == Color.green))
            {
                titleLabel.setText("Logging in....");
                loginButton.setEnabled(false);
            }
        }
    }


    private static void createAndShowGUI() {

        JFrame.setDefaultLookAndFeelDecorated(true);
        JFrame frame = new JFrame("[=] JTextField of Dreams [=]");

        TextFieldExample demo = new TextFieldExample();
        frame.setContentPane(demo.createContentPane());
        
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(310, 200);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        //Schedule a job for the event-dispatching thread:
        //creating and showing this application's GUI.
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
}
When you run the program, it should look a bit like this.

Login Screen showing TextFields

Using the JTextFields, we can input a username and a password as you would expect. The JTextFields are very easy to set-up and use. They follow the same syntax as we have been learning previously.

The number passed as an argument when the JTextField object is instantiated (or created for those who don't know what that means!) is the number of letters you want visible on the TextField at once. This does not work right now, as we define the size of the JTextField manually...but when we begin to use LayoutManagers it will automatically size the field so it will only display the number of characters you want it to display (in this case 8).

Bear in mind, this is only for displaying of characters in a JTextField. You can scroll along the Textfield to see more of them. If you wish to limit the number of characters you can physically put in, we need to manually edit the Model-View-Controller structure which we will cover in the third section.
54
55
56
57
        usernameField = new JTextField(8);
        usernameField.setLocation(0, 0);
        usernameField.setSize(100, 30);
        panelForTextFields.add(usernameField);
Other than the creation of a JTextField, there is no code in that method that you have not seen before.
We still display it on this page so you can get a feel for how the GUI is put together.

The area you should be most interested in is the actionPerformed method for the Action Listener.

The first code you will not have seen before is the code on Line 107 dealing with the extraction of text from one of the textfields.
We start by extracting the text using usernameField.getText(). This, crazily enough, gets the text from the username field.
We use .trim() to remove the white space from the text we get, as white space can mess up a string comparison.
Finally we use .compare("Bob") to compare the string we got from the usernameField with the string Bob.
108
            if(usernameField.getText().trim().compareTo("Bob") == 0)
Simply using if(usernameField.getText() == "Bob") does not work. You must use the compareTo() function when dealing with Strings.

For more information on Strings, have a look at the Swing API.

Swing's String API

The only other line of interest in this GUI is the line setting the button to be un-usable. Make sure you run the program and login with "Bob" as your username and "Robert" as your password. You will see the Login button is suddenly disabled.
By setting the button to .setEnabled(false) it stops the button from being enabled!. This can be very useful when you are trying to lead a user through a large GUI, or just disabling options when they are not currently available.
134
                loginButton.setEnabled(false);
This example of a Login Screen is ok, but there are things we can do to both restrict the users inputs and hide them from people looking behind them.

Questions

Before we move onto the JPasswordField...

Question 1. What is the int passed as an argument during instantiation for?

  • a) Telling the LayoutManager what size to make the box.
  • b) Telling the System how many characters are allowed in the box.
  • c) Telling the Label how far away to be.

Question 2. How do you disable a widget on your GUI?

  • a) .setEnabled(false);
  • b) .setDisabled(true);
  • c) .setPhasersTo(kill);

Question 3. When comparing Strings in an if statement, what must we use?

  • a) = =
  • b) .compareTo()
  • c) .sameAs()




Back Top Next
Email Me
Code Style


Required Lessons

External Links

Created and Edited by Stuart Davidson
All Rights Reserved ©

Valid XHTML 1.0 Strict