4 Ways to Create an AWT TextField

The following example illustrates creating an AWT TextField using its four constructors. This tutorial will also cover all core methods of TextField class.

import java.awt.*;
class AWTTextField extends Frame
{
TextField t1,t2,t3,t4;

    public AWTTextField()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("TextField in AWT Demo");
        setLayout(new FlowLayout());
       
        t1=new TextField();
        t2=new TextField(20);
        t3=new TextField("Third textfield");
        t4=new TextField("Fourth textfield",40);
       
        // Set max visible chars
        t1.setColumns(25);
       
        // Set echo char (for password fields)
        t2.setEchoChar('*');
       
        // Set text
        t1.setText("First textfield");
       
        // Select all
        t3.selectAll();
       
        // Set position of caret   
        t4.setCaretPosition(2);
       
        // Make t1 non-editable
        t1.setEditable(false);
       
        // Set custom background,foreground
        t1.setBackground(Color.LIGHT_GRAY);
        t1.setForeground(Color.RED);
       
        // Add all textfields
        add(t1);
        add(t2);
        add(t3);
        add(t4);
       
        // Print textfield properties
        System.out.println("Is t1 editable? "+t1.isEditable());
        System.out.println("Is echo char set for t1? "+t1.echoCharIsSet());
        System.out.println("Echo char for t2 "+t2.getEchoChar());
        System.out.println("Selected text in t3 "+t3.getSelectedText());
        System.out.println("Caret position in t4 "+t4.getCaretPosition());
       
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        new AWTTextField();
    }
}

AWTTextField(): Code illustrating creation of AWT TextField is invoked here.
new AWTTextField(): Create an object for the class AWTTextField

4 Ways to Create an AWT TextField in Java
Next: Creating AWT TextArea in Java
Previous: Creating an AWT Button


Posted by at on

Tags: Abstract Window Toolkit,