TOPIC:-
The Swing Buttons-JButton, JToggleButton, Check
Boxes, Radio Buttons
WHAT IS SWING:-
Swing is a Java Foundation Classes [JFC] library and an extension of
the Abstract Window Toolkit [AWT]. Java Swing offers much-
improved functionality over AWT, new components, expanded
components features, and excellent event handling with drag-and-drop
support.
THE SWING BUTTONS:-
Swing buttons are interactive components that users can click
or toggle to perform actions in a Java Swing application.
TYPES OF BUTTONS:-
Type Swing Class Use Case
Standard clickable
Push Button JButton
button
Switch between
Toggle Button JToggleButton
ON/OFF states
Multiple options can
Check Box JCheckBox
be selected
Select one from a
Radio Button JRadioButton
group
Menu actions (File,
Menu Item JMenuItem
Edit, etc.)
CHECK BOXES:-
A JCheckBox is a Swing component that lets the user Select or Deselect
an option. It's commonly used when multiple options can be selected
independently
Syntax:-
JCheckBox checkBox = new JCheckBox("Label Text");
Radio Buttons:-
JRadioButton is a Swing component that allows the user to select one
option from a group of choices. Unlike checkboxes, radio buttons are
mutually exclusive when grouped
Syntax:-
JRadioButton radioButton = new JRadioButton("Option Name");
JButton :-
A JButton is a Swing component that creates a button the user can
click to trigger an action — such as submitting a form, opening a new
window, or performing a calculation
Syntax:-
JButton button = new JButton("Click Me");
JToggleButton :-
A JToggleButton is a button that has two states:
Selected and Deselected. It's useful when you want a user to
toggle a setting on/off.
Syntax:-
JToggleButton toggleButton = new JToggleButton("Toggle Me");
import javax.swing.*; ButtonGroup bg = new ButtonGroup();
import java.awt.*; bg.add(r1); bg.add(r2);
import java.awt.event.*; JToggleButton toggle = new JToggleButton("Toggle");
JButton btn = new JButton("Submit");
public class ShortSwingExample {
btn.addActionListener(e -> {
public static void main(String[] args) {
String msg = "Checkbox: " + cb.isSelected() +
JFrame f = new JFrame("Short
Example"); "\nRadio: " + (r1.isSelected() ? "Male" : r2.isSelected() ?
"Female" : "None") +
f.setLayout(new FlowLayout()); "\nToggle: " + (toggle.isSelected() ? "On" : "Off");
f.setSize(300, 200); JOptionPane.showMessageDialog(f, msg);
});
f.setDefaultCloseOperation(JFrame.EXIT_ON
_CLOSE);
f.add(cb); f.add(r1); f.add(r2); f.add(toggle); f.add(btn);
f.setVisible(true);
JCheckBox cb = new
JCheckBox("Accept"); }
JRadioButton r1 = new }
JRadioButton("Male");
JRadioButton r2 = new
JRadioButton("Female");