Friday, July 29, 2011

Set JCheckBox Label using JTextField

Output:
Code:

/**

* File: changeJCheckBoxLabel.java

* Tiltle: Set JCheckBox Label using JTextField

* Author: http://java-code-complete.blogspot.com

*/



//Java Core Package

import javax.swing.*;

//Java Extension Package

import java.awt.*;

import java.awt.event.*;



public class changeJCheckBoxLabel extends JFrame {



//Initializing JTextField and JCheckBox

private JTextField field;

private JCheckBox box;



//Setting up GUI

public changeJCheckBoxLabel() {



//Setting up the Title of the Window

super("Set JCheckBox Label using JTextField");



//Set Size of the Window (WIDTH, HEIGHT)

setSize(310,90);



//Exit Property of the Window

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);



//Constructing JTextField and JCheckBox

field = new JTextField("Enter Text Here...",25);

box = new JCheckBox("Default Label",true);



//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 JCheckBox label using JTextField

box.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 JCheckBox components to the container

pane.add(field);

pane.add(box);



/**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) {

changeJCheckBoxLabel cjcb = new changeJCheckBoxLabel();

}

}


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 JCheckBox label using JTextField

box.setText(field.getText());



//The JTextField will be empty after Enter key is pressed ready for the next input.

field.setText(null);

}

}

);

No comments:

Post a Comment