Output:
Code:
/** * File: textFieldToWindowTitle.java * Tiltle: Change Window Title using JTextField * 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 textFieldToWindowTitle extends JFrame { //Initializing JTextField private JTextField field; //Setting up GUI public textFieldToWindowTitle() { //Setting up the Title of the Window super("Change Window Title"); //Set Size of the Window (WIDTH, LENGTH) setSize(350,80); //Exit Property of the Window setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Constructing JTextField with a size of 30 with a specified string "Enter Text Here..." field = new JTextField("Enter Text Here...",30); //Setting up the container ready for the components to be added. Container pane = getContentPane(); setContentPane(pane); //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) { //Setting up the Window Title using JTextField setTitle("Change Window Title: "+field.getText()); //The JTextField will be empty after Enter key is pressed ready for the next input. field.setText(null); } } ); //Adding the JTextField component to the container pane.add(field, BorderLayout.NORTH); /**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) { textFieldToWindowTitle wt = new textFieldToWindowTitle(); } }
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) { //Setting up the Window Title using JTextField setTitle("Change Window Title: "+field.getText()); //The JTextField will be empty after Enter key is pressed ready for the next input. field.setText(null); } } );