Friday, July 29, 2011

Copy JTextField Text to JLabel

Design Free Website with Free Internet Marketing Tools

Output:
Code:

/**
 * File: jtextfieldToJLabel.java
 * Tiltle: Copy JTextField Text to JLabel
 * Author: http://java-program-sample.blogspot.com
 */

//Java Core Package
import javax.swing.*;
//Java Extension Package
import java.awt.*;
import java.awt.event.*;

public class jtextfieldToJLabel extends JFrame {
 
 //Initializing JTextField and JLabel
 private JTextField field;
 private JLabel label;

 //Setting up GUI
    public jtextfieldToJLabel() {
     
     //Setting up the Title of the Window
     super("Copy JTextField Text to JLabel");

     //Set Size of the Window (WIDTH, HEIGHT)
     setSize(280,80);

     //Exit Property of the Window
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

     //Constructing JTextField and JLabel
     field = new JTextField("Enter Text Here...",23);
     label = new JLabel("Label");

     //Setting up the container ready for the components to be added.
     Container pane = getContentPane();
     setContentPane(pane);
     
     //Setting up the container layout
     FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
     pane.setLayout(flow);
     
     //Implemeting Even-Listener on JTextField's reference name "field" using ActionListener
  field.addActionListener(
  new ActionListener() {
   
   //Handle JTextField event if Enter key is pressed
   public void actionPerformed(ActionEvent event) {
    
    //Copy JTextField Text to JLabel
    label.setText(field.getText());
    
    //The JTextField will be empty after Enter key is pressed ready for the next input.
    field.setText(null);

   }
  }
  );

     //Adding the JTextField and JLabel components to the container
     pane.add(field);
     pane.add(label);

     /**Set all the Components Visible.
      * If it is set to "false", the components in the container will not be visible.
      */
     setVisible(true);
    }
    
 //Main Method
    public static void main (String[] args) {
     jtextfieldToJLabel jtl = new jtextfieldToJLabel();
 }
}

Important Part of the Program:

//Implemeting Even-Listener on JTextField's reference name "field" using ActionListener
  field.addActionListener(
  new ActionListener() {
   
   //Handle JTextField event if Enter key is pressed
   public void actionPerformed(ActionEvent event) {
    
    //Copy JTextField Text to JLabel
    label.setText(field.getText());
    
    //The JTextField will be empty after Enter key is pressed ready for the next input.
    field.setText(null);

   }
  }
  );

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Hostgator Discount Code