0% found this document useful (0 votes)
0 views

Java Exp16irshad

Uploaded by

irshad0371234786
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Java Exp16irshad

Uploaded by

irshad0371234786
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Experiment No.

16

GUI application with Event Handling

Name:chaudhary irshad ali

Roll No:7 Year:SE

Div:A Batch:A1

Aim: - WAP to change background color as Red, Green, Blue using 3 toggle Buttons

import javax.swing.*;

import java.awt.*;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

public class ColorToggleButtons extends JFrame implements ActionListener {

private JPanel panel;

private JToggleButton redButton;

private JToggleButton greenButton;

private JToggleButton blueButton;

public ColorToggleButtons() {

// Set up the frame

setTitle("Toggle Color Background");

setSize(400, 300);

setDefaultCloseOperation(EXIT_ON_CLOSE);

setLayout(new BorderLayout());

// Create a panel for color change

panel = new JPanel();


panel.setBackground(Color.WHITE); // Initial background color

add(panel, BorderLayout.CENTER);

// Create toggle buttons

redButton = new JToggleButton("Red");

greenButton = new JToggleButton("Green");

blueButton = new JToggleButton("Blue");

// Add action listeners

redButton.addActionListener(this);

greenButton.addActionListener(this);

blueButton.addActionListener(this);

// Create a panel for buttons

JPanel buttonPanel = new JPanel();

buttonPanel.add(redButton);

buttonPanel.add(greenButton);

buttonPanel.add(blueButton);

add(buttonPanel, BorderLayout.SOUTH);

@Override

public void actionPerformed(ActionEvent e) {

// Reset all buttons to unselected

if (e.getSource() == redButton) {

if (redButton.isSelected()) {

panel.setBackground(Color.RED);
greenButton.setSelected(false);

blueButton.setSelected(false);

} else {

panel.setBackground(Color.WHITE);

} else if (e.getSource() == greenButton) {

if (greenButton.isSelected()) {

panel.setBackground(Color.GREEN);

redButton.setSelected(false);

blueButton.setSelected(false);

} else {

panel.setBackground(Color.WHITE);

} else if (e.getSource() == blueButton) {

if (blueButton.isSelected()) {

panel.setBackground(Color.BLUE);

redButton.setSelected(false);

greenButton.setSelected(false);

} else {

panel.setBackground(Color.WHITE);

public static void main(String[] args) {

// Run the application

SwingUtilities.invokeLater(() -> {

ColorToggleButtons frame = new ColorToggleButtons();


frame.setVisible(true);

});

OUTPUT:

You might also like