Friday, July 29, 2011

Set JRadioButton Label using JTextField

Program Description:

The program below is a simple Java Code that lets you customize you own JRadioButton label using JTextField so in this way, your JRadioButton label is changeable. It gives you the capability to change its label easily without going in to codes.

Output:
Code:

/**

* File: changeJRadioButtonLabel.java

* Tiltle: Set JRadioButton 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 changeJRadioButtonLabel extends JFrame {



//Initializing JTextField and JRadioButton

private JTextField field;

private JRadioButton button;



//Setting up GUI

public changeJRadioButtonLabel() {



//Setting up the Title of the Window

super("Set JRadioButton 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 JRadioButton

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

button = new JRadioButton("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 JRadioButton 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 JRadioButton 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) {

changeJRadioButtonLabel jtrl = new changeJRadioButtonLabel();

}

}


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 JRadioButton 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);

}

}

);

No comments:

Post a Comment