set Background Color Java


In Java AWT, using Color object, the background color of frame or any component or any graphical figure can be changed. In this tutorial set Background Color Java, the background color of frame, button and graphics is changed.

Know how to create different colors with Java AWT Color.

import java.awt.*;
public class SetBackgroundColor extends Frame
{
  public SetBackgroundColor()
  {
    setBackground(Color.cyan);   // sets predefined color cyan to background of frame

    setLayout(new FlowLayout());
    Color clr1 = new Color(187, 157, 177);
    Button btn = new Button("CLICK HERE");
    btn.setBackground(clr1);          // sets background color to Button btn
    add(btn);

    setSize(300, 200);
    setVisible(true);
  }
  public void paint(Graphics g)
  {
    g.setColor(Color.red);
    g.fillRect(80, 100, 150, 75);
  }
  public static void main(String args[])
  {
    new SetBackgroundColor();
  }
}

set Background Color JavaOutput Screenshot on set Background Color Java

setBackground(Color.cyan);

This statement changes background color of frame to cyan color. cyan is one of the 13 predefined colors of Java.

setLayout(new FlowLayout());
Color clr1 = new Color(187, 157, 177);
Button btn = new Button(“CLICK HERE”);
btn.setBackground(clr1);

A button object btn is created and set with a background color of clr1. The color components 187 is red, 157 is green color and 177 is blue color.

public void paint(Graphics g)
{
g.setColor(Color.red);
g.fillRect(80, 100, 150, 75);
}

The rectangle background is filled with red color.

Learn clearly Java AWT: Java AWT Button – Learning GUI – 8 Steps

Learn internals of Java Event Handling.

Leave a Comment

Your email address will not be published.