How to create java swing jcheckbox with detail examples

-Java swing JCheckBox is an object that allows us to select multiple properties. For example, when filling out information for a viewer, that person has money, homes, cars. That person may have three or no one at all.

Create Java swing JCheckBox

-We will create a JFrame with java swing JCheckBoxes as shown below:
java-swing-jcheckbox-examples
-The JFrame consists of two main parts: the left part contains three JCheckBoxes, the right part contains three corresponding JLabels. We will first create the java swing JCheckBox.

-File name: MyJCheckBox.java
java-swing-jcheckbox-examples
-Continue MyJCheckBox.java
java-swing-jcheckbox-examples
-About the interface I do not say again, in the code also comments relative. I just talked about the java swing JCheckBox creation.
-In the createCheckBox (String name) method, we used the JCheckBox constructor: checkBox = new JCheckBox (name); Here's how to create a JCheckBox with the corresponding text. In addition, we have other initialization methods such as:

  •  JCheckBox (): Create a JCheckBox with no text, no icon, no check.
  •  JCheckBox (Action a): Create a JCheckBox with an action
  •  JCheckBox (Icon icon): Create a JCheckBox with an icon
  •  JCheckBox (Icon icon, boolean selected): Create JCheckBox with icon and set selection.
  •  JCheckBox (String text, boolean selected): Create JCheckBox with text and set selection.
  •  JCheckBox (String text, Icon icon): Create JCheckBox with text, with icon
  •  JCheckBox (String text, Icon icon, boolean selected): Create JCheckBox with text, icon, settings selected.

Getting events for java swing JCheckBox

-To catch an event when checking the java swing checkBox we need addItemListener for each checkBox. The createCheckBox () method is modified as follows:
java-swing-jcheckbox-examples
-Now, our class needs to implements the ItemListener interface and override the public void itemStateChanged (ItemEvent e) method. This method is the method for us to do the job when check box. In this example, we will trigger the check event every time we check a checkbox. Then check that the check box is selected or deselected to set whether or not to display the corresponding JLabel.
java-swing-jcheckbox-examples
-To check whether the java swing  jcheckBox is selected, use the isSelected () method. So our whole program will be written as follows:

-File name: MyJCheckBox.java
java-swing-jcheckbox-examples
-Continue MyJCheckBox.java
java-swing-jcheckbox-examples
-Continue MyJCheckBox.java
java-swing-jcheckbox-examples
-More about how to customize java swing boderlayout with detail example:

Comments