Create Check Box in Java

This section illustrates you how to create a Check Box component in Java Swing.In this section, you can learn simply creating the Check Box in Java Swing. Check Boxes are created in swing by creating the instance of the JCheckBox class using it's constructor which contains the string which has to be shown beside the check box on the frame or window


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

/**
 *
 * @author AHCHUTHAN
 */
public class Checkboxtest extends JFrame {

    private JTextField field;
    private JCheckBox bold, italic;

    Checkboxtest() {
        super("Testing Checkbox");
        Container c = getContentPane();
        c.setLayout(new FlowLayout());
        field = new JTextField("Font Stayle Changes", 20);
        field.setFont(new Font("counter", Font.PLAIN, 14));
        bold = new JCheckBox("BOLD");
        italic = new JCheckBox("ITALIC");

        CheckBoxHandler handler = new CheckBoxHandler();
        bold.addItemListener(handler);
        italic.addItemListener(handler);

        c.add(bold);
        c.add(italic);
        c.add(field);
        setSize(400, 400);
        setVisible(true);

    }

    public static void main(String args[]) {
        Checkboxtest b = new Checkboxtest();
        b.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public class CheckBoxHandler implements ItemListener {

        private int valBold = Font.PLAIN;
        private int valItalic = Font.PLAIN;

        public void itemStateChanged(ItemEvent e) {
            if (e.getSource() == bold) {
                valBold = bold.isSelected()
                        ? Font.BOLD : Font.PLAIN;
            }

            if (e.getSource() == italic) {
                valItalic = italic.isSelected()
                        ? Font.ITALIC : Font.PLAIN;
            }
            field.setFont(new Font("counter",
                    valBold + valItalic, 14));


        }
    }
}
Download

Output of this program :

Popular posts from this blog

The n-queens problem in Java

Convert infix to postfix using stack in Java