Creating Custom Colors

You can create custom colors in Java by specifying their Standard Red Green Blue (sRGB) value. sRGB defines a color by the amount of red, green, and blue present in the color. Each value ranges from 0 (none of that color) to 255 (the maximum amount).

The constructor Color(int, int, int) takes arguments representing the red, green, and blue values. The following code draws a panel that displays light orange text (230 red, 220 green, 0 blue) on a dark red (235 red, 50 green, 50 blue) background:

import java.awt.*;
import javax.swing.*;

public class GoBucs extends JPanel {
    Color lightOrange = new Color(230, 220, 0);
    Color darkRed = new Color(235, 50, 50);

    public void paintComponent(Graphics comp) {
        Graphics2D comp2D = (Graphics2D) comp;
        comp2D.setColor(darkRed);
        comp2D.fillRect(0, 0, 200, 100);
        comp2D.setColor(lightOrange);
        comp2D.drawString("Go, Buccaneers!", 5, 50);
    }
}


Note

sRGB values enable the creation of 16.5 million possible combinations, though most computer monitors only offer a close approximation for most of them. For guidance on whether burnt-midnight blue goes well with medium-faded-baby green, read Sams Teach Yourself Color Sense While Waiting in Line at This Bookstore.


This example calls the fillRect() method of Graphics2D to draw a filled-in rectangle using the current color.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.166.149