swing

Java Swing Checkbox Example

1. Introduction

In this article, Java swing checkbox will be discussed. checkbox is to present whether an item has been selected or unselected. In Java swing, JCheckBox is the component to fulfill this function. Different actions could be performed, and different states could also be displayed to the users, if we add action listener or action handler to the checkbox.

In Java swing, JCheckBox is inherited from AbstractButton and JToggleButton. It inherits all the methods from its parent classes. It could be constructed through following constructors:

  • JCheckBox(): creates an checkbox without text nor icon
  • JCheckBox(Action e): creates an checkbox where properties are taken from the provided action
  • JCheckBox(Icon icon): creates an checkbox with an icon
  • JCheckBox(Icon icon, boolean selected): creates an checkbox with an icon and specifies whether this icon has been selected or not
  • JCheckBox(String text): creates an checkbox with text
  • JCheckBox(String text, boolean selected): creates an checkbox with text and specifies whether this text has been selected or not
  • JCheckBox(String text, Icon icon): creates an checkbox with an icon and text
  • JCheckBox(String text, Icon icon, boolean selected):  creates an checkbox with text and icon, and specifies whether these two have been selected or not

Further detailed information about the JCheckBox could be referred to the official Oracle documents.

2. Examples on java swing checkbox

For the following example parts on JCheckBox, Java 8 and Eclipse IDE (version Mars 4.5.0) are used.

2.1 Simple example of java swing checkbox

In this example, five JCheckBox are created, added to the panel and frame, with the title to be set to “Fruits”. Five different fruits are named by “Apple”, “Banana”, “Grape”, “Orange” and “Pear”. Then these can be selected by the checkbox.

Below is the Java code for this example:

simpleCheckbox.java

package javaCodeGeeks;

/*
 * A simple swing checkbox example with different constructors
 */

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;

public class simpleCheckbox {

	public static void main(String[] args) {
		// Create and set up a frame window
		JFrame.setDefaultLookAndFeelDecorated(true);
		JFrame frame = new JFrame("Simple checkbox demo");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		// Define the panel to hold the checkbox	
		JPanel panel = new JPanel();
		
		// Create checkbox with different constructors
		JCheckBox checkbox1 = new JCheckBox("Apple", true);
		JCheckBox checkbox2 = new JCheckBox("Banana");		
		JCheckBox checkbox3 = new JCheckBox("Grape", true);
		JCheckBox checkbox4 = new JCheckBox("Orange");
		JCheckBox checkbox5 = new JCheckBox("Pear", true);
		
		// Set up the title for the panel
		panel.setBorder(BorderFactory.createTitledBorder("Fruits"));
		
		// Add the checkbox into the panels 
		panel.add(checkbox1);
		panel.add(checkbox2);
		panel.add(checkbox3);
		panel.add(checkbox4);
		panel.add(checkbox5);
		
		// Add the panel into the frame
		frame.add(panel);
		
		// Set the window to be visible as the default to be false
		frame.pack();
		frame.setVisible(true);

	}

}

Run this code, and following result should show up:

simpleCheckbox
simple Checkbox demo

As we can see from the above figure, “Apple”, “Grape” and “Pear” are selected automatically, while “Banana” and “Orange” not. The reason for this is we have set the three fruits to be selected, while the other two not. The following code could explain the difference.

		JCheckBox checkbox1 = new JCheckBox("Apple", true);
		JCheckBox checkbox2 = new JCheckBox("Banana");

2.2 Other settings on checkbox

As we’ve described in introduction part, that JCheckBox is inherited from AbstractButton and JToggleButton, we can have different settings on checkbox.

For example, we can set font for different checkbox with the code similar to the following:

checkbox1.setFont(new java.awt.Font("Arial", Font.BOLD, 18));

In this example, we’ve set the font for the checkbox “Apple” to be “Arial” with the font to be 18 and bolded. The effect of this setting can be shown as below:

font
Font setting on checkbox

Also, we can set the background and foreground with different colors. For example, we can set the color of checkbox “Banana” to be “RED” with the following code:

checkbox2.setForeground(Color.RED);

The result of this setting is shown below:

color
Color setting on checkbox

Lastly, we can set the mnemonic key by specifying the key code defined in java.wt.event.KeyEvent. For instance, keyboard ‘A’ could be set to mnemonic key by following code:

		checkbox1.setMnemonic(KeyEvent.VK_A);
		checkbox1.setSelected(true);

The result for this setting is that you can use the keyboard ‘alt’ and ‘A’ to select or unselect the specified checkbox. Figure below shows this effect:

mnemonic
Mnemonic setting on checkbox

2.3 Checkbox with event listener

For checkbox, the more common usage should be combining it with event listener. With the event listener added, the checkbox can act different actions.

In the following example, we have different names (“Alex”, “Jessica”, “Lily”, “Steven”) on panel1. When we click any name, the output panel shows that the name is selected. However, when we unselect the name, the output panel shows that the name is unselected.

Below is the Java code for this example:

checkboxWithEvent.java

package javaCodeGeeks;

/*
 * A checkbox example with event listener
 */

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import javax.swing.JCheckBox;

import java.awt.GridLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

public class checkboxWithEvent {	
	// Create different checkbox
	public static JCheckBox checkbox1 = new JCheckBox("Alex");
	public static JCheckBox checkbox2 = new JCheckBox("Jessica");
	public static JCheckBox checkbox3 = new JCheckBox("Lily");		
	public static JCheckBox checkbox4 = new JCheckBox("Steven");

	public static void main(String[] args) {
		// Create and set up a frame window
		JFrame.setDefaultLookAndFeelDecorated(true);
		JFrame frame = new JFrame("Checkbox with event listener");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		// Define the panel to hold the checkbox	
		JPanel panel1 = new JPanel();
		JPanel panel2 = new JPanel();
		JLabel msg = new JLabel("", JLabel.CENTER);
			
		// Set up the title for the panel
		panel1.setBorder(BorderFactory.createTitledBorder("Name"));	
		panel2.setBorder(BorderFactory.createTitledBorder("Output"));		
		
		// Add the checkbox into the panels 	
		panel1.add(checkbox1);
		panel1.add(checkbox2);
		panel1.add(checkbox3);
		panel1.add(checkbox4);
		
		panel2.add(msg);
		
		// Add action listener
		checkbox1.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				if (e.getStateChange() == 1) {
					msg.setText("Alex is selected");
				} else {
					msg.setText("Alex is unselected");
				}
			}
		});

		checkbox2.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				if (e.getStateChange() == 1) {
					msg.setText("Jessica is selected");
				} else {
					msg.setText("Jessica is unselected");
				}
			}
		});
		
		checkbox3.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				if (e.getStateChange() == 1) {
					msg.setText("Lily is selected");
				} else {
					msg.setText("Lily is unselected");
				}
			}
		});
		
		checkbox4.addItemListener(new ItemListener() {
			public void itemStateChanged(ItemEvent e) {
				if (e.getStateChange() == 1) {
					msg.setText("Steven is selected");
				} else {
					msg.setText("Steven is unselected");
				}
			}
		});
		
		// Add the panel into the frame
		frame.setLayout(new GridLayout(2, 1));
		frame.add(panel1);
		frame.add(panel2);
		
		// Set the window to be visible as the default to be false
		frame.pack();
		frame.setVisible(true);
	}
	
}

When we run this code, we can see the result below with nothing in the output panel.

output
Output with nothing

However, after we select the checkbox of Alex, the output shows that Alex is selected as below:

selected
Checkbox selected

Then we unselected Alex, the output shows that Alex is unselected:

unselected
Checkbox unselected

The final note for the Java swing checkbox is the difference between checkbox and radio button. For checkbox, we can select multiple checkbox, while in radio button, only one button can be selected at one time.

3. Download the Source Code

This was an example of Checkbox in Java Swing.

Download
You can download the source code of this example here: checkboxexample.zip

Jun Wu

Jun (Steven) Wu is a current Master student in Computer Science & Engineering department of University of Nebraska Lincoln (Lincoln, NE, USA). His current interests focus on Programming Languages (Java, Python), Relational Database (MySQL), NoSQL Database (Apache Cassandra, MongoDB), and Computer Networks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button