How do I get the color of a screen pixel?

The example here show us how to get the color of a pixel in the screen. We use the Robot.getPixelColor(int x, int y) method to obtain the Color of the pixel.

package org.kodejava.awt;

import java.awt.Color;
import java.awt.Robot;
import java.awt.AWTException;

public class ColorPickerDemo {
    public static void main(String[] args) {
        try {
            Robot robot = new Robot();

            // The pixel color information at 20, 20
            Color color = robot.getPixelColor(200, 200);

            // Print the RGB information of the pixel color
            System.out.println("Red   = " + color.getRed());
            System.out.println("Green = " + color.getGreen());
            System.out.println("Blue  = " + color.getBlue());

        } catch (AWTException e) {
            e.printStackTrace();
        }
    }
}

Example output of code snippet above:

Red   = 35
Green = 38
Blue  = 53

How do I change an applet background color?

By default, the applet will usually have a grey background when displayed in a web browser. If you want to change it then you can call the setBackground(java.awt.Color) method and choose the color you want. Defining the background color in the init() method will change the color as soon as the applet initialized.

package org.kodejava.applet;

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;

public class BackgroundColorApplet extends Applet {
    public void init() {
        // Here we change the default grey color background of an 
        // applet to yellow background.
        setBackground(Color.YELLOW);
    }

    public void paint(Graphics g) {
        g.setColor(Color.BLACK);
        g.drawString("Applet background example", 0, 50);
    }
}

Now we have the applet code ready. To enable the web browser to execute the applet create the following html page.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Applet Background Color</title>
</head>
<body>
<applet code="org.kodejava.applet.BackgroundColorApplet"
        height="150" width="350">
</applet>
</body>
</html>
** Deprecated: The Applet API is deprecated since JDK 9, no replacement.