JTextField in Java GUI (Swing) | Complete Guide

Jtextfield java

When we are working with Graphical user interfaces the most common way to take text input from the user is to use the text fields. In Java Swing, we also have a specific component for the same purpose. Yes, you are right we use JTextField to take text input from the users. will the input may be the name of the user or it may be the password or email. To keep it short and simple we do need some way to take input from the user and for the text input, we use JTextFields. JTextField class in Java Swing library have many forms. we will discuss them in detail. we have JPassword filed to take the password from the user or something that we do not want to display to the user when the user is typing. sometimes it is important for the users to make some text hidden.

To keep thing simple I will create a simple program that will use the JTextField and I will explain the code with the help of comments as well as I will show some topics and methods in detail after the program.

package AlixaProDev;

import javax.swing.*;
import java.awt.*;

public class TextFiledBasics extends JFrame {
// Declare a JTextFiled type reference
JTextField textField;

TextFiledBasics(){
// creating the Object of the JTextField
textField = new JTextField();
// setting the bounds of the TextField
textField.setBounds(0,0,200,20);
// setting the text of the JtextField
textField.setText("Write your text here");

// do not forgot to add our textfield to the window
this.add(textField);

// setting up our JFrame window
this.setSize(new Dimension(200,200));
// we will working with the Flowlayout this time
this.setLayout(new BorderLayout());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}

public static void main (String[] args) {
new TextFiledBasics();
}

}

Now, let's discuss some of the most important methods of the JTextField and then we will create a very beautiful small application with the help of the JTextFiled class.

textField.setEditable(true);

This is a very important method. there are sometimes when we want to make the text field disable or enable for the input. This method accepts the boolean value either true or false. if we set it to the boolean value true then it means we can edit here. for example, we can set up a condition that after this condition ore event happening we have to disable the textfile. setting the parameter value to false will disable it.  a very good example will be when we want a user to do some task after that we will enable the text field. we will do a program in which we will use this method.

textField.setBackground(Color.cyan);

To customize the look and feel of the Text field we can use multiple methods one of them is changing the background colour. we can change the background we can use this method. this method accepts the Color Object. we can create our custom colours as well we look into that in the Future Articles as well.

textField.setForeground(Color.red);

SO times we need to change the font color. we can do it with the help of this method. but this method will alone not set the font color into red unless we call another method after it. the method which should be after this method is the following method. these two methods work together to change the colour fo the red.

textField.setFont(new Font("MV Boli",Font.BOLD,24));

By calling this method we can set the font of the TextField. This method helps us to specify which type of Fonts we want to use is the font of the text field. this method accepts the Font object. we will look into this as well. 

textField.setCaretColor(Color.black);

With the help of this method, we can set the colour of the Caret. Yes, we Java swing gives us the capability of whatever we want we can even customize the caret. this method will set the colour of the caret to black. 

package AlixaProDev;

import javax.swing.*;
import java.awt.*;

public class TextFiledBasics extends JFrame {
// Declare a JTextFiled type reference
JTextField textField;

TextFiledBasics(){
// creating the Object of the JTextField
textField = new JTextField();
// setting the bounds of the TextField
textField.setBounds(0,0,400,30);
// setting the text of the JtextField
textField.setText("Write your text here");

textField.setCaretColor(Color.black);
textField.setBackground(Color.cyan);
textField.setForeground(Color.red);
textField.setFont(new Font("MV Boli",Font.BOLD,24));
textField.setOpaque(true);


// do not forgot to add our textfield to the window
this.add(textField);

// setting up our JFrame window
this.setSize(new Dimension(400,200));
// we will working with the Border Layout this time
this.setLayout(new BorderLayout());
this.setIconImage(new ImageIcon("Images/icon.png").getImage());
this.setTitle("working with JTextField");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}

public static void main (String[] args) {
new TextFiledBasics();
}

}

The outPut of the Above Code

There are some Important Methods in the JTextField that we have not discussed in our previous article. This is the Part Second of the JTextField, Java Swing Library component.

All Java Swing Components triggers some events that the programmers have to handle. All Java swing components have different event triggers. so we will not look to the overall event handling but we will look into the common events that can be handled in the JTextFiled.

The important thing about every graphical user interface is that they are all event-driven. What this means to you? will it means that some event occurs on the Graphical user interface components and we listen to this event and we then handle it with our code. now the code that handles the event is called the event handler code. when we are working on a high-level program we have a separate package for the event handler code.

Creating Login form in Java Swing with JTextField

We will create a simple login type application. First, we will make it simple and then we will do some customization is will. also, I will try my best to explain every statement of the code.

package AlixaProDev;

import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;


// creating our login system. do not overthing this is a
// simple demo
// we will of course make big applications in the near
// funture is well
public class JtextFieldDemo2 extends JFrame {

// Crating our References we will initializing all of them
// in the constructor of the class

// creating our JtextFields for the differnt fields
// that we want to collect infornamtion from the user.

JTextField userName;
JTextField email;

// crating the Submit button reference
JButton submitbtn;

// This is a another subclass of the JtextField
// will talk about the methods of this class in the
// upcomming codes
// for now just note that anything that we
// writhe in their will be hidden
// and only sombe big dots will be appearing on the screen.
JPasswordField password;


// crating some differnt label for the user to
// let the user where to put what information

JLabel userLabel;
JLabel emailLabel;
JLabel passwordLabel;


JtextFieldDemo2(){

// initializing different fields that we already have declared
// above. Remember we could intialize them in here but
// in order to access them outside we have to initialize it in the
// global scope.
userName = new JTextField();
email = new JTextField();
password = new JPasswordField();
userLabel = new JLabel("Name:");
emailLabel = new JLabel("Email:");
passwordLabel = new JLabel("Password:");
submitbtn = new JButton("Submit");

// plaicing our Labels in the Proper position. I
// have already talked about the methods
// in the previous Articles
userLabel.setBounds(10,20,110,30);
emailLabel.setBounds(10,50,110,30);
passwordLabel.setBounds(10,80,110,30);
userName.setBounds(120,20,400,30);
email.setBounds(120,50,400,30);
password.setBounds(120,80,400,30);

// customizing the JtextFields
//1. lets create border for our JtextField
Border border = BorderFactory.createLineBorder(Color.green);
userName.setBorder(border);
submitbtn.setBounds(250,130,100,30);
this.add(userName);
this.add(email);
this.add(password);
this.add(userLabel);
this.add(emailLabel);
this.add(passwordLabel);
this.add(submitbtn);
this.setResizable(false);
this.setSize(new Dimension(600,500));
this.setLocation(new Point(500,300));
this.setLayout(null);
this.getContentPane().setBackground(Color.PINK);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);

}

public static void main (String[] args) {
new JtextFieldDemo2();
}



}

Well Now copy this code and run it in your IDE. you will see the output. I will put the picture of the output very soon. but we need to do some customization to the code so that our GUI looks professional. The source code is well documented and the above code does not contain anything new that is worth discussing. we have just put the methods that we have discussed before and have made the application. One thing worth noticing is the setBorderMethod() that set the Border of the JTextField. we have to first create the Border and then we have to set it with the help of the Method.

Now there are some important events that can be occurred on the JTextField that we can handle it. We will talk in-depth about event handling in the next Articles. but for now, we will do some basic event handling for our login Form that we have created with the help of the upper code. we will customize that is changing the colour of the JTextField which is currently in focus. we will look into that in the upcoming code. I strongly recommend before running the code. look at the comments and the methods and guess the output of the code then it will be easy for you to learn about these methods this is the only way you can learn programming.

This code is to create a simple login form

package AlixaProDev;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;

// We will Implement the ActionListner Interface
// to listen to the action and events that can be
// occured on the JtextFiled.
public class JtextFieldDemo2 extends JFrame {
// setting up some important refernces
JTextField userName;
JTextField email;
JButton submitbtn;
JPasswordField password;
JLabel userLabel;
JLabel emailLabel;
JLabel passwordLabel;

// creating Font for the JtextFields and Jlabels
Font myFavFont;

JtextFieldDemo2(){
userName = new JTextField();
email = new JTextField();
password = new JPasswordField();

userLabel = new JLabel("Name:");
emailLabel = new JLabel("Email:");
passwordLabel = new JLabel("Password:");

submitbtn = new JButton("Submit");
submitbtn.setBackground(Color.blue);
submitbtn.setForeground(Color.white);

// the constructor accpts three parametters
myFavFont = new Font("MV BOli",Font.BOLD,25);


userLabel.setBounds(10,20,110,30);
emailLabel.setBounds(10,60,110,30);
passwordLabel.setBounds(10,100,130,30);

userName.setBounds(140,20,350,30);
email.setBounds(140,60,350,30);
password.setBounds(140,100,350,30);

submitbtn.setBounds(250,150,100,30);

userName.setFont(myFavFont);
email.setFont(myFavFont);
// the character that is used in the password field
password.setEchoChar('*');

// setting up the fonts
passwordLabel.setFont(myFavFont);
userLabel.setFont(myFavFont);
emailLabel.setFont(myFavFont);
userName.setBackground(Color.cyan);
password.setBackground(Color.cyan);
email.setBackground(Color.cyan);
password.setFont(myFavFont);


// adding components to the JFrame
this.add(userName);
this.add(email);
this.add(password);
this.add(userLabel);
this.add(emailLabel);
this.add(passwordLabel);
this.add(submitbtn);

// lets register our JtextFiedls with the
// DocumentListner interface when some event
// occur on these text field then it will be
// handled by the following Methods.


userName.getDocument().addDocumentListener
(new TextFiledEventHandler(userName));
email.getDocument().addDocumentListener
(new TextFiledEventHandler(email));
password.getDocument().addDocumentListener
(new TextFiledEventHandler(password));



this.setTitle("Login Form");
this.setIconImage(new ImageIcon("Images/icon.png").getImage());
this.setResizable(false);

this.setSize(new Dimension(600,550));
this.setLocation(new Point(500,300));
this.setLayout(null);
this.getContentPane().setBackground(Color.PINK);

this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);

}

public static void main (String[] args) {
new JtextFieldDemo2();
}

// creating inner class to make it easier to pass parameter
private class TextFiledEventHandler implements DocumentListener{

JTextField textField;
TextFiledEventHandler(JTextField textField){
this.textField = textField;
}

@Override
public void insertUpdate (DocumentEvent e) {
textField.setBorder(BorderFactory.createLineBorder(Color.green));
}

@Override
public void removeUpdate (DocumentEvent e) {
textField.setBorder(BorderFactory.createLineBorder(Color.red));
}

@Override
public void changedUpdate (DocumentEvent e) {
textField.setBorder(BorderFactory.createLineBorder(Color.BLUE));

}
}
}

This code will produce the following form. I have inserted some of the values do not worry about it.

How can I use JTextField to get two numbers from a user and show the sum on a JLabel Java?

This is a most asked questions that is asked in most of the cases. SO here i will guide you how to create such program. You already know how can you do it, as we have studied most of the methods that we can use in this program. Create a JPanel and add two JTextField to that JPanel. Now and the JPanel to JFrame and get text from the JTExt Field and Add them.

Summary and Conclusion:-

We learned about how we can create JTextField. We also apply our knowledge to create a log in form with Java Swing. If you are interested in other Programming tutorials please visit my youtube channel Code with Ali.

AlixaProDev

I’m Ali, Founder of alixaprodev.com. I am a Software developer, and I love to write articles to help students, developers, and learners. I started alixaprodev.com because of my love for Python, Java, and WebDev.

Post a Comment (0)
Previous Post Next Post