How to use JTextField in Java using Swing Framework API ?.

Program to demonstrate working of JTextField in Java using Swing API

package com.hubberspot.code;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;


public class JTextFieldDemo {

 public static void main(String[] args) {

  // 1. Create a simple frame by creating an object 
  // of JFrame.
  JFrame frame = new JFrame();

  // 2. Create a label by creating an Object of class 
  // JLabel
  JLabel label = new JLabel();

  // 3. set the text of label as "Name : "
  label.setText("Name : ");

  // 4. Create a textfield by creating an Object of class 
  // JTextField
  JTextField textfield = new JTextField();

  // 5. set the text of textfield as "add text ... "
  textfield.setText("add text ... ");

  // 6. We create a Layout for Swing Components
  // here we are using FlowLayout.
  frame.setLayout(new FlowLayout());

  // 7. We add the textfield and label to frame
  frame.add(label);
  frame.add(textfield);

  // 8. set a operation when a user close the frame, here it 
  // closes the frame and exits the application
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  // 9. Give frame a size in pixels as say 300,300 
  frame.setSize(200, 100);

  // 10. Give the frame a title "JTextField Demo" by calling 
  // setTitle method on frame object
  frame.setTitle("JTextField Demo");

  // 11. after adding textfield and label, we make it 
  // visible on the frame by calling the method as 
  // setVisible and passing value as true.
  frame.setVisible(true);
 }

}



Output of the program :