Using Color in Java Swing

To use color in Java Swing, we can follow these steps:

Import the java.awt.Color package.

import java.awt.Color;

Create a Color object with the desired color.

Color myColor = new Color(red, green, blue); // replace red, green and blue with the RGB values (0-255) of the desired color

Alternatively, you can use one of the predefined colors in the Color class. For example:

Color redColor = Color.RED;
Color blueColor = Color.BLUE;
Color greenColor = Color.GREEN;

Set the color of a Swing component using the setBackground() or setForeground() methods.

Example:

JPanel myPanel = new JPanel();
myPanel.setBackground(myColor); // set the background color of the panel
myPanel.setForeground(redColor); // set the foreground color of the panel

We can also set the color of other Swing components such as buttons, labels, text fields, etc. using the same methods.

Note that the setBackground() and setForeground() methods are inherited from the java.awt.Component class, which is the superclass of all Swing components.

Example Code

The complete example code of how to use color in the Java Swing application is given below:

import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class ColorDemo {
	public static void main(String[] args) {
        JFrame frame = new JFrame("Color Demo"); // create a JFrame
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // set the default close operation
        frame.setSize(300, 300); // set the size of the frame

        JPanel panel = new JPanel(); // create a JPanel
        panel.setBackground(Color.RED); // set the background color of the panel to red

        // Displaying label with blue color
        JLabel message = new JLabel("Coder Sathi");
        message.setForeground(Color.BLUE);
        panel.add(message);
        
        frame.add(panel); // add the panel to the frame
        frame.setVisible(true); // make the frame visible
    }
}

In this example, we create a JFrame and set its close operation and size. Then, we create a JPanel and set its background color to red using the setBackground() method. We also add a JLabel to display a message in blue color and add this label to the panel. Finally, we add the panel to the frame and make the frame visible using the add() and setVisible() methods, respectively.

When we run this code this displays the panel inside the frame has a red background and the text has a blue color.

Output

Using Color in Java Swing color in java swing
Using Color in Java Swing 2