How do I read the status of Caps Lock key?

This example show you how to detect if the Caps Lock key is in active mode.

package org.kodejava.example.awt;

import java.awt.Toolkit;
import java.awt.event.KeyEvent;

public class CapsLockState {
    public static void main(String[] args) {
        // Get the locking state of the Caps Lock button. If it is "on" this method
        // return boolean true value.
        boolean isOn = Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK);

        System.out.println("CapsLock button is " + (isOn ? "on" : "off"));
    }
}

How do I get the number of buttons on the mouse?

MouseInfo provides methods for getting information about the mouse, such as mouse pointer location and the number of mouse buttons.

package org.kodejava.example.awt;

import java.awt.*;

public class MouseNumberOfButtons {
    public static void main(String[] args) {
        // Get the number of buttons on the mouse. On systems without a mouse, returns -1. 
        // HeadlessException if GraphicsEnvironment.isHeadless() returns true.
        int numberOfButtons = MouseInfo.getNumberOfButtons();
        System.out.println("Mouse Number Of Buttons = " + numberOfButtons);
    }
}

How do I get the location of mouse pointer?

MouseInfo provides methods for getting information about the mouse, such as mouse pointer location and the number of mouse buttons.

package org.kodejava.example.awt;

import java.awt.*;

public class MouseInfoDemo {
    public static void main(String[] args) {
        int i = 0;
        while (i < 10) {
            // Get the location of our mouse x and y coordinate using
            // the PointerInfo.getLocation() method which return an 
            // instance of Point.
            Point location = MouseInfo.getPointerInfo().getLocation();
            double x = location.getX();
            double y = location.getY();

            System.out.println("x = " + x);
            System.out.println("y = " + y);

            try {
                Thread.sleep(1000);
                i++;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

How do I get screen’s display mode information?

This example shows graphics devices display mode information such as the display width, height, refresh rate and bit depth. This information can be obtained from GraphicsDevice.getDisplayMode() method which return an instance of java.awt.DisplayMode.

We can also get the size of a screen using the following example How do I get my screen size?, but this example can handle only a single screen.

package org.kodejava.example.awt;

import java.awt.*;

public class GettingScreenDisplayModeInformation {
    public static void main(String[] args) {
        // Get local graphics environment
        GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();

        GraphicsDevice[] devices = env.getScreenDevices();

        int sequence = 1;
        for (GraphicsDevice device : devices) {
            System.out.println("Screen Number [" + (sequence++) + "]");
            System.out.println("Width       : " + device.getDisplayMode().getWidth());
            System.out.println("Height      : " + device.getDisplayMode().getHeight());
            System.out.println("Refresh Rate: " + device.getDisplayMode().getRefreshRate());
            System.out.println("Bit Depth   : " + device.getDisplayMode().getBitDepth());
            System.out.println("");
        }
    }
}

An example of the program result:

Screen Number [1]
Width       : 1280
Height      : 1024
Refresh Rate: 60
Bit Depth   : 32

Screen Number [2]
Width       : 1280
Height      : 800
Refresh Rate: 60
Bit Depth   : 32

How do I get number of available screens?

This code shows how to get number of available screen devices on the local machine or local graphics environment. We obtain the number of screens by getting the length of array returned by GraphicsEnvironment.getScreenDevices() method.

This process can produce a HeadlessException to happen if we try to run this code on a machine that doesn’t have a screen device with it.

package org.kodejava.example.awt;

import java.awt.GraphicsEnvironment;
import java.awt.GraphicsDevice;
import java.awt.HeadlessException;

public class GettingNumberOfScreen {
    public static void main(String[] args) {
        try {
            // Get local graphics environment
            GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();

            // Returns an array of all of the screen GraphicsDevice objects.
            GraphicsDevice[] devices = env.getScreenDevices();

            int numberOfScreens = devices.length;
            System.out.println("Number of available screens = " + numberOfScreens);
        } catch (HeadlessException e) {
            // We'll get here if no screen devices was found.
            e.printStackTrace();
        }
    }
}

How do I create mouse event using Robot class?

In this example we are automating the process of creating mouse event using the java.awt.Robot class.

package org.kodejava.example.awt;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.InputEvent;

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

            // Move mouse cursor to 200, 200
            robot.mouseMove(200, 200);

            // Press the mouse button #1.
            robot.mousePress(InputEvent.BUTTON1_MASK);
            robot.mouseRelease(InputEvent.BUTTON1_MASK);

            // Scroll the screen up for a mouse with a wheel support.
            robot.mouseWheel(-100);
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }
}

How do I get the colour 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.example.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 the pixel color information at 20, 20
            Color color = robot.getPixelColor(20, 20);

            // 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();
        }
    }
}

How do I create key press event using Robot class?

In this example we use the java.awt.Robot class to generate a key press event. We can call the keyPress(int keyCode) method to produce this event.

package org.kodejava.example.awt;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;

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

            // Create a three seconds delay.
            robot.delay(3000);

            // Generating key press event for writing the QWERTY letters
            robot.keyPress(KeyEvent.VK_Q);
            robot.keyPress(KeyEvent.VK_W);
            robot.keyPress(KeyEvent.VK_E);
            robot.keyPress(KeyEvent.VK_R);
            robot.keyPress(KeyEvent.VK_T);
            robot.keyPress(KeyEvent.VK_Y);
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }
}

How do I create a screen capture using Robot class?

In this example you’ll see how to create a screen capture / screenshot and save it as an image file such a PNG image. Some classes are use in this program including the java.awt.Robot, java.awt.image.BufferedImage and javax.imageio.ImageIO.

package org.kodejava.example.awt;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.io.File;
import java.io.IOException;

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

            // Capture screen from the top left in 200 by 200 pixel size.
            BufferedImage bufferedImage = robot.createScreenCapture(
                    new Rectangle(new Dimension(200, 200)));

            // The captured image will the written into a file called
            // screenshot.png
            File imageFile = new File("screenshot.png");
            ImageIO.write(bufferedImage, "png", imageFile);
        } catch (AWTException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How do I get the available font family names?

package org.kodejava.example.awt;

import java.awt.Font;
import java.awt.GraphicsEnvironment;

public class FontFamilyNameList {
    public static void main(String[] args) {
        // Get all available font family names from GraphicsEnvironment
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        String familyNames[] = ge.getAvailableFontFamilyNames();

        // Iterates familyNames array to display the available font's family names
        for (String familyName : familyNames) {
            System.out.println("Family names: " + familyName);
        }        
    }
}