Java Program to Display String with Background Color as Cyan in a Frame


This is a Java Program to Display String with Background Color as Cyan in a Frame

Problem Description

We have to write a program in Java such that it creates a frame with background color as cyan and a text with color red is written in the frame.

Expected Input and Output

For displaying string with background color as cyan, we have the following set of input and output.


To Display the Frame :

On the execution of the program,
it is expected that the frame has background color as cyan, and also
displays the text "The Background of Frame is Cyan" in frame with red color.
Problem Solution

1. Create the frame.
2. Set the background color of frame as cyan using setBackground(Color.CYAN).
3. Create a text with required font type and size.
4. Set the color of text to red using setForeground(
5. Display the frame.

Program/Source Code

Here is source code of the Java Program to perform arithmetic operations. The program is successfully compiled and tested using javac compiler on Fedora 30. The program output is also shown below.

  1. /*Java Program to Display Text with Background Color as Cyan*/
  2. import javax.swing.*;
  3. import java.awt.*;
  4. class Background_Cyan
  5. {
  6.     //Driver function
  7.     public static void main(String args[])
  8.     {
  9.         //Create a frame
  10. 	JFrame frame = new JFrame("Cyan Text");
  11. 	frame.setSize(400,400);
  12. 	frame.setLayout(new FlowLayout());
  13. 	frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  14. 	frame.getContentPane().setBackground(Color.CYAN);
  15. 	//Write some text to the frame
  16. 	String str="The Background of Frame is Cyan";
  17. 	JLabel text = new JLabel(str);
  18. 	text.setFont(new Font("Serif",Font.ITALIC,20));
  19. 	frame.add(text);
  20. 	//Set Background Color of Text as red
  21. 	text.setForeground(;
  22. 	//Display the frame
  23. 	frame.setVisible(true);
  24.     }
  25. }
Program Explanation

1. To set the background color of frame, use the setBackground() function.
2. To set the foreground color of text, use the setForeground() function.

Runtime Test Cases

Here’s the run time test cases to display text with background color as cyan.

Test case 1 – To view the frame.

Sanfoundry Global Education & Learning Series – Java Programs.


Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn