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 the 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 and 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 are used to represent the column numbers in a new empty TextField.
- JTextField(String text): The parameter string text is used to represent an initialized given string with a new empty text field.
- JTextField(String text, int columns): This is the constructor that is used to create an empty text field with the string provided along with the specified number of columns.
- JTextField(Document doc, String text, int columns): This is used to make use of the given storage model along with 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 is used to set the specified number of columns within a text field.
- setFont(Font f): This function is used to display and set the font of the text field displayed text.
- addActionListener(ActionListener I): this method is used to set the action listener to the text field.
- Int getColumns(): This method is used to get 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 is able to enter a small text value. Whenever a text entry is confirmed by the user, 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 inputs from the user it is advisable to make use of the text area.
Let us see some code for the basic creation of the textfield and its 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 makes use of 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: This box can be edited and also provides a menu of various sets of strings to choose from.
- JSpinner: JSpinner is used to combine a formatted text field along with a couple of small buttons that enable the user to choose among 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
This is a guide to JTextField in Java. Here we discuss the Methods and Examples of JTextField in Java with Outputs and also the usage of TextFields. You may also have a look at the following articles to learn more –
41 Online Courses | 29 Hands-on Projects | 305+ Hours | Verifiable Certificate of Completion
4.8
View Course
Related Courses