How do I create JCheckBox component?

This example demonstrate a various way to create JCheckBox component. Here you can also see how the handle an event when the checkbox is clicked by user.

package org.kodejava.swing;

import javax.swing.*;
import java.awt.*;
import java.util.Objects;

public class CheckBoxDemoCreate extends JFrame {
    public CheckBoxDemoCreate() throws HeadlessException {
        initialize();
    }

    private void initialize() {
        setSize(500, 500);
        setTitle("JCheckBox Demo");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new FlowLayout(FlowLayout.LEFT));

        // Creating checkbox with text label
        JCheckBox checkBoxA = new JCheckBox("Selection A");

        // Creating checkbox with text label a set the state into checked
        JCheckBox checkBoxB = new JCheckBox("Selection B", true);

        // Creating checkbox with text label and a default unselected image icon
        ImageIcon icon = new ImageIcon(
                Objects.requireNonNull(
                        this.getClass().getResource("/images/lightbulb_off.png")));
        JCheckBox checkBoxC = new JCheckBox("Selection C", icon);
        // Add action listener to listen for click and change the image icon
        // respectively
        checkBoxC.addActionListener(e -> {
            JCheckBox checkBox = (JCheckBox) e.getSource();
            if (checkBox.isSelected()) {
                checkBox.setIcon(new ImageIcon(
                        Objects.requireNonNull(
                                this.getClass().getResource("/images/lightbulb.png"))));
                // Perform other actions here!
            } else {
                checkBox.setIcon(new ImageIcon(
                        Objects.requireNonNull(
                                this.getClass().getResource("/images/lightbulb_off.png"))));
                // Perform other actions here!
            }
        });

        getContentPane().add(checkBoxA);
        getContentPane().add(checkBoxB);
        getContentPane().add(checkBoxC);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new CheckBoxDemoCreate().setVisible(true));
    }
}
Swing JCheckBox Demo

Swing JCheckBox Demo

How do I get modifiers of a class object?

package org.kodejava.lang.reflect;

import java.lang.reflect.Modifier;

public class ClassModifier {
    public static void main(String[] args) {
        getClassModifier(String.class);
        getClassModifier(TestA.class);
        getClassModifier(TestB.class);
    }

    private static void getClassModifier(Class<?> clazz) {
        int modifier = clazz.getModifiers();

        // Return true if the integer argument includes the public modifier,
        // false otherwise.
        if (Modifier.isPublic(modifier)) {
            System.out.println(clazz.getName() + " class modifier is public");
        }

        // Return true if the integer argument includes the protected modifier,
        // false otherwise.
        if (Modifier.isProtected(modifier)) {
            System.out.println(clazz.getName() + " class modifier is protected");
        }

        // Return true if the integer argument includes the private modifier,
        // false otherwise.
        if (Modifier.isPrivate(modifier)) {
            System.out.println(clazz.getName() + " class modifier is private");
        }

        // Return true if the integer argument includes the static modifier,
        // false otherwise.
        if (Modifier.isStatic(modifier)) {
            System.out.println(clazz.getName() + " class modifier is static");
        }

        // Return true if the integer argument includes the final modifier,
        // false otherwise.
        if (Modifier.isFinal(modifier)) {
            System.out.println(clazz.getName() + " class modifier is final");
        }

        // Return true if the integer argument includes the abstract modifier,
        // false otherwise.
        if (Modifier.isAbstract(modifier)) {
            System.out.println(clazz.getName() + " class modifier is abstract");
        }
    }

    protected static final class TestA {
    }

    private abstract class TestB {
    }
}

The code snippet prints the following output:

java.lang.String class modifier is public
java.lang.String class modifier is final
org.kodejava.lang.reflect.ClassModifier$TestA class modifier is protected
org.kodejava.lang.reflect.ClassModifier$TestA class modifier is static
org.kodejava.lang.reflect.ClassModifier$TestA class modifier is final
org.kodejava.lang.reflect.ClassModifier$TestB class modifier is private
org.kodejava.lang.reflect.ClassModifier$TestB class modifier is abstract

How do I create object using Constructor object?

The example below using a constructor reflection to create a string object by calling String(String) and String(StringBuilder) constructors.

package org.kodejava.lang.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class CreateObjectDemo {
    public static void main(String[] args) {
        Class<String> clazz = String.class;

        try {
            Constructor<String> constructor = clazz.getConstructor(String.class);

            String object = constructor.newInstance("Hello World!");
            System.out.println("String = " + object);

            constructor = clazz.getConstructor(StringBuilder.class);
            object = constructor.newInstance(new StringBuilder("Hello Universe!"));
            System.out.println("String = " + object);
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}

How do I get constructors of a class object?

Below is an example that showing you how to get constructors of a class object. In the code below we get the constructors by calling the Class.getDeclaredConstructors() or the Class.getConstructor(Class[]) method.

package org.kodejava.lang.reflect;

import java.lang.reflect.Constructor;

public class GetConstructors {
    public static void main(String[] args) {
        Class<String> clazz = String.class;

        // Get all declared constructors and iterate the constructors to get their
        // name and parameter types.
        Constructor<?>[] constructors = clazz.getDeclaredConstructors();
        for (Constructor<?> constructor : constructors) {
            String name = constructor.getName();
            System.out.println("Constructor name= " + name);

            Class<?>[] parameterTypes = constructor.getParameterTypes();
            for (Class<?> c : parameterTypes) {
                System.out.println("Param type name = " + c.getName());
            }
            System.out.println("----------------------------------------");
        }

        // Getting a specific constructor of the java.lang.String
        try {
            Constructor<String> constructor = String.class.getConstructor(String.class);
            System.out.println("Constructor     = " + constructor.getName());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}

How do I get field of a class object and set or get its value?

A refection demo to get fields of a class’s object and set or get their values.

package org.kodejava.lang.reflect;

import java.util.Date;
import java.lang.reflect.Field;

public class GetSetFieldDemo {
    public static Date now;
    public Long id;
    public String name;

    public static void main(String[] args) {
        GetSetFieldDemo demo = new GetSetFieldDemo();
        Class<? extends GetSetFieldDemo> clazz = demo.getClass();

        try {
            // Get field id, set it value and read it back
            Field field = clazz.getField("id");
            field.set(demo, 10L);
            Object value = field.get(demo);
            System.out.println("Value = " + value);

            // Get static field date, set it value and read it back
            field = clazz.getField("now");
            field.set(null, new Date());
            value = field.get(null);
            System.out.println("Value = " + value);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }

    }
}

The output of the code snippet:

Value = 10
Value = Wed Oct 06 06:18:23 CST 2021