TextField in Java AWT


The textField component allows the user to edit single line of text.When the user types a key in the text field the event is sent to the TextField.

Constructor Used for
TextField() new text field component.
TextField(String text) new text field initialized with the given string text to be displayed.
TextField(int columns) new textfield (empty) with given number of columns.
TextField(String text, int columns) new text field with the given text and given number of columns (width).

This is a Java program that demonstrates the use of TextFields in AWT (Abstract Window Toolkit) for creating a simple GUI application.

  • The program creates a window using the Frame class and sets its size and layout. It then creates a TextField object and two Label objects to display the text entered in the TextField object. One Label displays the current value of the TextField, and the other Label displays the value of the TextField when the user presses the Enter key.
  • The program adds TextListener and ActionListener objects to the TextField object to detect when the user enters text or presses the Enter key. When the user enters text, the current value of the TextField is displayed in one Label, and when the user presses the Enter key, the value of the TextField is displayed in the other Label.
  • Finally, the program adds the TextField and Label objects to the window and sets a WindowAdapter object to handle the closing of the window when the user clicks on the close button.

Overall, this program shows how to use TextFields in AWT to create a simple GUI application with event handling.

Source Code

package awtDemo;
 
import java.awt.*;
import java.awt.event.*;
//TextField in AWT
class MyApp  extends Frame implements TextListener,ActionListener{
 
	TextField txt;
	Label l1,l2;
 
	public MyApp() {
		super("Tutor Joes");
		setSize(1000,600);//w,h
		setLayout(null);
		setVisible(true);
 
		txt=new TextField();
		txt.setBounds(10, 50, 250, 30);
 
		l1=new Label("----");
		l1.setBounds(300, 50, 250, 30);
		txt.addTextListener(this);
		txt.addActionListener(this);
 
		l2=new Label("----");
		l2.setBounds(10, 100, 250, 30);
 
		add(txt);
		add(l1);
		add(l2);
 
		//Close Button Code
		this.addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent we) {
				System.exit(0);
			}
		});
	}
 
	@Override
	public void actionPerformed(ActionEvent e) {
		l2.setText(txt.getText());
 
	}
 
	@Override
	public void textValueChanged(TextEvent e) {
		l1.setText(txt.getText());
 
	}
}
public class app{
	public static void main(String[] args) {
		MyApp frm=new MyApp();
	}
 
}
 
To download raw file Click Here

Output

Java AWT


Basic Programs