Updated July 1, 2023
Introduction to JTextField in Java
When we talk about Java programming language, there are two segments associated with it; one is Core Java, and the other is Advanced Java. The features such as OOPs concepts such as polymorphism, abstraction, encapsulation, etc., and other features such as Exception Handling, Collections, applets, etc., are associated with Core Java, whereas features such as Swing, Hibernate, Struts, etc. form component of Advanced Java. JTextField is also a feature of Java Swing, which allows the single-line editing of the text. The main intention is to keep its stability and compatibility intact with java.awt.TextField forms an integral part of the javax.swing package. It inherits the JTextComponent class and makes use of the SwingConstant interface.
Let us study a bit about the various constructors present in the JTextField:
The constructors belonging to this class are:
- JTextField(): These are the constructors that are responsible for the creation of the new TextField.
- JTextField(int columns): As the name suggests, the parameter columns represent the column numbers in a new empty TextField.
- JTextField(String text): The parameter string text represents an initialized given string with a new empty text field.
- JTextField(String text, int columns): This constructor creates an empty text field with the provided string and the specified number of columns.
- JTextField(Document doc, String text, int columns): This uses the given storage model and the specified number of columns.
Methods of JTextField
Let us now read about some of the major methods in the JTextField in Java.
- setColumns(int n): As the name suggests, this method sets the specified number of columns within a text field.
- setFont(Font f): This function displays and set the font of the text field displayed text.
- addActionListener(ActionListener I): This method sets the action listener to the text field.
- Int getColumns(): This method gets the column numbers in the text field.
Making Use of Text Fields
The main aim of a text field is to set a basic level of text control with which the user can enter a small text value. Whenever the user confirms a text entry, which is usually done by pressing the Enter key, the text field can be seen firing an action event. If you are required to obtain multiple lines of input from the user, it is advisable to use the text area.
Let us see some code for the basic textfield creation and usage.
public class TDemo extends JPanel implements ActionListener {
public JtField tField;
public JtArea tArea;
public TDemo() {
super(new Layout());
tField = new JtField(20);
tField.addActionListener(this);
tArea = new JtArea(5, 20);
tArea.setEditable(false);
JScrollPane scrollPane = new JScrollPane(tArea);
Constraints c = new Constraints();
c.gridwidth = Constraints.REMAINDER;
c.fill = Constraints.HORIZONTAL;
add(tField, c);
c.fill = Constraints.BOTH;
c.wx = 1.0;
c.wy = 1.0;
add(scrollPane, c);
}
public void act(ActionEvent evt) {
String txt = tField.getText();
tArea.append(txt);
tField.selectAll();
tArea.setCaretPosition(tArea.getDocument().getLength());
}
private static void GUI() {
JFrame frame = new JFrame("TDemo");
frame.add(new TDemo());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) throws IOException{
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
GUI();
}
});
}
}
Swing API uses several classes that either include the textfields or are the varieties of the textfields.
- JFormattedTextField: A JTextField subclass that gives you the authority to specify the set of legal characters that are user enterable.
- JPasswordField: A subclass that does not relate to showing user-typed characters.
- JComboBox: You can edit this box and it provides a menu of various strings to choose from.
- JSpinner: JSpinner combines a formatted text field with a couple of small buttons that enable the user to choose between the previous and the next available value.
Examples of JTextField in Java
Let us now have a look at some of the examples
Example #1
Code:
import javax.swing.*;
import java.awt.event.*;
class Jteobjxt exteobjnds JFrame implements ActionListeobjner {
static JLabel l;
static JButton b;
static JFrame f;
static JTField t;
// creating default constructor for Jteobjxt example
Jteobjxt()
{
}
// public static void main class
public static void main(String[] args)
{
// new frame creation
f = new JFrame("JTField");
// new label creation
l = new JLabel("");
// new button creation
b = new JButton("submit button createobjd");
// new object creation
Jteobjxt teobj = new Jteobjxt();
// adding addActionListeobjner to my created button
b.addActionListeobjner(teobj);
// creating a column of 16 numbers
t = new JTField(16);
// panel creation
JPanel p = new JPanel();
// adding Jtextfield and buttons to panel
p.add(t);
p.add(b);
p.add(l);
// adding panel to frame created
f.add(p);
// setting the size of frame created earlier
f.setSize(300, 300);
f.show();
}
// checking whether the button is pressed or not
public actionPerformed(ActionEvent e)
{String s1 = e.getActionCommand();
if (s1.equalsIgnoreCase("submit")) {
l.setJteobjxt(t.getJteobjxt());
// set the field object as the blank value
t.setJteobjxt(" ");
}
}
}
Output:
Example #2
Code:
import javax.swing.*;
import java.io.*;
class TextEg
{
public static void main(String args[]) throws IOException
{
JFrame f= new JFrame("Example of TextField ");
//variable declaration
JTextField t12,t22;
t12=new JTextField("Welcome!");
t12.setBounds(10,100, 100,30);
//declaring new example
t22=new JTextField("new example");
//setting bounds
t22.setBounds(10,150, 100,30);
//adding into frames
f.add(t12); f.add(t22);
f.setSize(200,200);
f.setVisible(true);
}
}
Output:
Example #3
Code:
import javax.swing.*;
import java.io.*;
import java.awt.event.*;
public class Teg implements ActionListener{
JTextField tf12,tf22,tf32;
JButton b12,b22;
Teg(){
JFrame f2= new JFrame();
tf12=new JTextField();
tf12.setBounds(10,50,100,20);
tf22=new JTextField();
tf22.setBounds(10,50,100,20);
tf32=new JTextField();
tf32.setBounds(10,50,100,20);
//setting the setEditable as False
tf32.setEditable(false);
//addition operator
b12=new JButton("+");
b12.setBounds(10,50,100,20);
//subtraction operator
b22=new JButton("-");
b22.setBounds(10,50,100,20);
//this is used to refer to the current value
b12.addActionListener(this);
b22.addActionListener(this);
//addition into all frames
f2.add(tf12);f2.add(tf22);f2.add(tf32);f2.add(b12);f2.add(b22);
f2.setSize(100,200);
//setting layout (default) to null
f2.setLayout(null);
f2.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s12=tf12.getText();
String s22=tf22.getText();
int a2=Integer.parseInt(s12);
int b2=Integer.parseInt(s22);
int c2=0;
//conditional statement start
if(e.getSource()==b12){
c2=a2+b2; //addition
}else if(e.getSource()==b22){
c2=a2-b2; //subtraction
}
//printing final result
String res=String.valueOf(c2);
tf32.setText(res);
}
public static void main(String[] args) {
new Teg();
} }
Output:
Recommended Articles
We hope that this EDUCBA information on “JTextField in Java” was beneficial to you. You can view EDUCBA’s recommended articles for more information.