Explain the four types of swing buttons with demonstration program
Answer:-
Types of Swing Buttons
- JButton – A standard push button.
- JToggleButton – A button that can be toggled ON/OFF.
- JCheckBox – Allows multiple selections; checkbox-style button.
- JRadioButton – Allows single selection within a group.
All are part of the javax.swing
package.
Java Swing Program Demonstrating All Four Buttons
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class SwingButtonsDemo { public static void main(String[] args) { // Create JFrame JFrame frame = new JFrame("Swing Button Types"); frame.setSize(400, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setLayout(new FlowLayout()); // 1. JButton JButton jButton = new JButton("Click Me"); jButton.addActionListener(e -> JOptionPane.showMessageDialog(frame, "JButton clicked")); // 2. JToggleButton JToggleButton toggleButton = new JToggleButton("Toggle Me"); toggleButton.addItemListener(e -> { if (toggleButton.isSelected()) { toggleButton.setText("ON"); } else { toggleButton.setText("OFF"); } }); // 3. JCheckBox JCheckBox checkBox = new JCheckBox("I agree"); checkBox.addItemListener(e -> { String status = checkBox.isSelected() ? "Checked" : "Unchecked"; System.out.println("Checkbox is " + status); }); // 4. JRadioButton (Grouped) JRadioButton radio1 = new JRadioButton("Option A"); JRadioButton radio2 = new JRadioButton("Option B"); ButtonGroup group = new ButtonGroup(); group.add(radio1); group.add(radio2); // Add buttons to frame frame.add(jButton); frame.add(toggleButton); frame.add(checkBox); frame.add(radio1); frame.add(radio2); // Display the frame frame.setVisible(true); } }
How it works:
- JButton: Performs an action when clicked.
- JToggleButton: Changes state between ON and OFF.
- JCheckBox: Can be selected or unselected independently.
- JRadioButton: Only one in a group can be selected at a time.