This is a Java Program to Change the Background Colour of Applet by Clicking on Control Button
We have to write a program in Java such that it changes the background color of the frame to a random color every time the control key on the keyboard is pressed.
For changing the background color of frame, we have the following different sets of input and output.
1. Initial Background Color of Applet :
When the program is executed, it is expected that the applet initially has background color white.
2. To Change the Background Color of Applet :
Everytime the Control key on the keyboard is pressed, it is expected that the background color changes.
1. Initially, set the background color as white.
2. Add KeyListener to the applet.
3. When the control key is pressed, change the background color of applet to a random color.
Here is source code of the Java Program to change background color of applet. The program is successfully compiled and tested using javac compiler on Fedora 30. The program output is also shown below.
/*Java Program to Change Background Color of Applet*/
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Change_Background extends Applet implements KeyListener
{
//Function to initialize the applet
public void init()
{
setBackground(Color.white);
addKeyListener(this);
}
//Function to change background color of applet
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==KeyEvent.VK_CONTROL)
{
int R = (int)(Math.random()*100) % 255;
int G = (int)(Math.random()*100) % 255;
int B = (int)(Math.random()*100) % 255;
Color mycolor = new Color(R,G,B);
this.setBackground(mycolor);
}
}
//Empty function
public void keyReleased(KeyEvent e)
{
}
//Empty function
public void keyTyped(KeyEvent e)
{
}
}
/*
<applet code=Change_Background.class width=400 height=400>
</applet>
*/
To compile and run the program use the following commands :
>>>javac Change_Background.java >>>appletviewer Change_Background.java
1. Add KeyListener to the applet.
2. When any key is pressed, the function keyPressed is called.
3. The key code of Control key is available as KeyEvent.VK_CONTROL. Compare it with the key code of the key pressed.
4. If the Control key is pressed, generate three random integer whose value are in the range 0 to 255 and use them as the RGB value to create a color.
5. Set the color created by the random values as the background color of the applet.
Here’s the run time test cases for changing background color of applet.
Test case 1 – To View the Initial Color of Applet.
Test case 2 – To View the Color of Applet on Click of Control Button.
Test case 3 – To View the Color of Applet on Click of Control Button.
Sanfoundry Global Education & Learning Series – Java Programs.
If you find any mistake above, kindly email to [email protected]- Apply for Java Internship
- Practice BCA MCQs
- Check Java Books
- Check Programming Books
- Practice Programming MCQs