Java TextField Methods

This is second program on TextField, first being User Name Password Validation (applet version is also available). The methods like setColumns(), setText() and setFont(), getColumns() and getText() are used to set and get the properties.

Example on using Java TextField Methods
import java.awt.*;
public class TextFieldProperties extends Frame
{
  TextField tf1, tf2, tf3;
  public TextFieldProperties()
  {                                      // set the layout to frame
    setLayout(new FlowLayout());
                                            // create components
    tf1 = new TextField(15);
    tf2 = new TextField("I Display", 15);
    tf3 = new TextField();
                                             // beautification
    tf3.setColumns(20);
    tf3.setText("Your way 2 java");
    tf3.setBackground(Color.cyan);
    tf3.setForeground(Color.blue);
    tf3.setFont(new Font("Monospaced", Font.BOLD, 15));
                                             // adding components
    add(tf1);   add(tf2);   add(tf3);

    setTitle("Setting Properties");
    setSize(500, 200);
    setVisible(true);
  }
  public void paint(Graphics g)
  {
    g.drawString("tf3 Length : " + tf3.getColumns(), 50, 100);
    g.drawString("tf3 Text : " + tf3.getText(), 50, 120);
  }
  public static void main(String args[])
  {
    new TextFieldProperties();
  }
}


Java TextField Methods
Output screen of Java TextField Methods

tf1 = new TextField(15);
tf2 = new TextField("I Display", 15);

We know a constructor gives properties to an object at the time of object creation itself and is the case with TextField also. The tf1 creates a text field with 15 characters width but user can enter any number of characters and the extra characters entered can be seen using arrow keys. The second text field object tf2 by default displays a text "I Display" in the text field which user can change.

Explanation of Java TextField Methods

tf3 = new TextField( );
tf3.setColumns(20);
tf3.setText("Your way 2 java");
tf3.setBackground(Color.cyan);
tf3.setForeground(Color.blue);
tf3.setFont(new Font("Monospaced", Font.BOLD, 15));

The text field tf3 object is created without any properties, and later, properties are set explicitly with setXXX() methods. setColumns() method sets the width of the text field and setText() method places the text. Background and foreground colors are set with setBackground() and setForeground() methods. Similarly, font is set with setFont() method.

2 thoughts on “Java TextField Methods”

Leave a Comment

Your email address will not be published.