2. Abstract Window Toolkit (AWT), Swing and Event Handling

2.1 Develop a program that has only one button in the frame, clicking on the button cycles through the colors: red->green->blue, and so on. One color changes per click.(usegetBackGround() method to get the current color)

ChangeColor.java

import java.awt.*;
import java.awt.event.*;
public class ChangeColor extends Frame implements ActionListener
{
Button btnColor=new Button("Click to change");
ChangeColor()
{
setLayout(new FlowLayout());
add(btnColor);
btnColor.addActionListener(this);
setVisible(true);
setSize(800,500);
}
public void actionPerformed(ActionEvent ae)
{
Color c=getBackground();
if(c.equals(Color.white))
{
setBackground(Color.red);
}
else if(c.equals(Color.red))
{
setBackground(Color.green);
}
else if(c.equals(Color.green))
{
setBackground(Color.blue);
}
else
{
setBackground(Color.red);
}
}
public static void main(String arg[])
{
ChangeColor c=new ChangeColor();
}
}

Output



Run code to see proper output

Happy Coding