Create Radio Button with Text Field in Java

In this program, you will learn how to set the radio buttons in a group so that only one can be selected at a time.
This program shows five radio buttons with labeled by plain,bold,italic,boldItalic .This program also show a label which contains the text "Font style changes" but when you click on any radio button from a Button Group the text of the selected radio button is shown on the label and a message box will be shown with message holds the selected radio button label. This is done through the generating event for the different-different radio buttons.
Following are the screen shots for the result of the given program:
This is the method of the ActionEvent class which returns the source title in string of the generated event.

Java version of Radio Button is given bellow :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

 * @author ACHCHUTHAN
public class RadioButtonTest extends JFrame {

    private JTextField field;
    private JRadioButton plain, bold, italic, boldItalic;
    private Font plainFont, boldFont, italicFont, boldItalicFont;
    private ButtonGroup radioGroup;

    RadioButtonTest() {
        super("Testing Radiobutton");
        Container c = getContentPane();
        c.setLayout(new FlowLayout());

        field = new JTextField("Font style changes", 20);

        plain = new JRadioButton("plain", true);

        bold = new JRadioButton("bold", false);

        italic = new JRadioButton("italic", false);

        boldItalic = new JRadioButton("boldItalic", false);

        radioGroup = new ButtonGroup();

        plainFont = new Font("serif", Font.PLAIN, 14);
        boldFont = new Font("serif", Font.BOLD, 14);
        italicFont = new Font("serif", Font.ITALIC, 14);
        boldItalicFont = new Font("serif", Font.BOLD + Font.ITALIC, 14);

        plain.addItemListener(new RadioButtonHandler(plainFont));
        bold.addItemListener(new RadioButtonHandler(boldFont));
        italic.addItemListener(new RadioButtonHandler(italicFont));
        boldItalic.addItemListener(new RadioButtonHandler(boldItalicFont));
        setSize(275, 150);


    public class RadioButtonHandler implements ItemListener {
        private Font font;
        public RadioButtonHandler(Font f) {
            font = f;

        public void itemStateChanged(ItemEvent e) {

    public static void main(String args[]) {
        RadioButtonTest b = new RadioButtonTest();
Output of this program :

Post a Comment

Thank you for vising

Previous Post Next Post