Output:
Code:
/** * File: changeJButtonLabel.java * Tiltle: Set JButton Label 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 changeJButtonLabel extends JFrame { //Initializing JTextField and JButton private JTextField field; private JButton button; //Setting up GUI public changeJButtonLabel() { //Setting up the Title of the Window super("Set JButton Label using JTextField"); //Set Size of the Window (WIDTH, HEIGHT) setSize(280,90); //Exit Property of the Window setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Constructing JTextField and JButton field = new JTextField("Enter Text Here...",23); button = new JButton("Default 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) { //Setting JButton label using JTextField button.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 JButton components to the container pane.add(field); pane.add(button); /**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) { changeJButtonLabel jtbl = new changeJButtonLabel(); } }
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 JButton label using JTextField button.setText(field.getText()); //The JTextField will be empty after Enter key is pressed ready for the next input. field.setText(null); } } );