Swing JTextField Class



Swing JTextField Class :

package com.c4learn.swing;

import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class JTextFieldDemo {

  private JFrame mainFrame;
  private JLabel headLabel;
  private JLabel msgLabel;
  private JPanel mainPanel;

  public JTextFieldDemo() {
    mainFrame = new JFrame("Java Swing Examples");
    mainFrame.setSize(400, 400);
    mainFrame.setLayout(new GridLayout(3, 1));

    headLabel = new JLabel("JTextField Demo",JLabel.CENTER);
    msgLabel = new JLabel("Blank Value", JLabel.CENTER);
    mainPanel = new JPanel();
    mainPanel.setLayout(new FlowLayout());

    mainFrame.add(headLabel);
    mainFrame.add(mainPanel);
    mainFrame.add(msgLabel);
    mainFrame.setVisible(true);
  }

  public static void main(String[] args) {
    JTextFieldDemo demo = new JTextFieldDemo();
    demo.showListDemo();
  }

  private void showListDemo() {

    JLabel lblName = new 
          JLabel("Enter name : ", JLabel.RIGHT);
    
    final JTextField txtName = new JTextField(10);

    JButton btnDisplay = new JButton("Display Text");
    btnDisplay.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        String data = "Name : " + txtName.getText();
        msgLabel.setText(data);
      }
    });

    mainPanel.add(lblName);
    mainPanel.add(txtName);
    mainPanel.add(btnDisplay);
    mainFrame.setVisible(true);
  }
}

Output :

Swing JTextField Class