Background Colors in Java

Sheeraz Gul Nov 04, 2022
Background Colors in Java

This tutorial demonstrates how to change background colors in Java.

Background Colors in Java

Changing the background color in Java GUI is an easy operation. The method setBackground() is used to set and change the background color of a JFrame in Java.

Follow the steps below to set the background color for a JFrame in Java:

  • First of all, create a JFrame.
  • Now set the default close operation.
  • Then, set the preferred size.
  • Then, get the content pane and set the background color using the setBackground() method.
  • Set the visibility of the frame to true.

Let’s implement an example based on the above steps:

package delftstack;

import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
public class Demo {
    public static void main(String[] args) {
        JFrame DemoFrame = new JFrame();
        DemoFrame.setPreferredSize(new Dimension(450, 200));

The code above will set the background color of a given JFrame in Java. See the output:

Set Background

Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

Related Article - Java GUI