Checkbox in Java GUI | Quiz Style UI AWT Example
Creating a Checkbox in Java GUI is quite a simple process. Here, unlike the buttons we saw in a Java GUI program to add two numbers there is no addActionListener. We have addItemListener instead. Checkbox in Java GUI comes really handy when you are dealing with a quiz style setup.
We will see first how a checkbox in Java can be used to respond using itemStateChanged method in an example.
Checkbox in Java GUI Example
Here’s an example to tell you how Checkboxes appear in a GUI setup:
import java.awt.*; import java.net.*; import java.awt.event.*; public class LearnAWT extends Frame { Checkbox cb1; Checkbox cb2; Label l1; LearnAWT() { setTitle("Checkbox Program"); cb1 = new Checkbox("Psycho"); cb1.setBounds(100, 100, 100, 100); cb2 = new Checkbox("Moron"); cb2.setBounds(100, 180, 100, 100); l1 = new Label(); l1.setBounds(20, 30, 140, 100); add(l1); add(cb1); add(cb2); setSize(400,400); setLayout(null); setVisible(true); cb1.addItemListener(new ItemListener(){ public void itemStateChanged(ItemEvent e) { if(e.getStateChange() == 1) { l1.setText("He calls you a Psycho"); } } }); cb2.addItemListener(new ItemListener(){ public void itemStateChanged(ItemEvent e) { if(e.getStateChange() == 1) { l1.setText("He calls you Moron"); } } }); } public static void main(String []args) { new LearnAWT(); } }
Here we have made use of an ItemListener instead of an actionListener. The primary reason being a checkbox doesn’t have an actionListener. It has a focusListener, hierarchyListener, mouseListener etc. but doesn’t have actionListener under its aegis.
If you run the above program you will get a frame with two checkboxes in it like this:
As per the logic of the above program, checking on any box will return a text in a label. Go ahead and click on any of the checkbox. Here I have done it for you:
Here I have clicked on the first flag and hence the result.
If you are creating an MCQ design you need to keep adding Checkboxes. Then place a button and use the actionPerformed method to specify what clicking on the correct answer should flare.
I would leave that part as an exercise for you to perform. Let me know in the comment section how things fared.
1 Response
[…] How to Create a Checkbox in Java […]