DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
Developer Tools

How to Capture Full-Screen Screenshots in Java (Single Monitor, All Displays, and HiDPI)

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Java’s built-in java.awt.Robot. Call createScreenCapture(Rectangle) with a rectangle in screen coordinates, then write the returned BufferedImage with ImageIO. For one primary display, the complete program is:

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

public class FullScreenShot {
    public static void main(String[] args) throws Exception {
        Robot robot = new Robot();
        Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
        BufferedImage image = robot.createScreenCapture(new Rectangle(size));
        ImageIO.write(image, "png", new File("screenshot.png"));
    }
}

The program captures the primary screen and creates screenshot.png in the process’s working directory. The same API can capture a chosen monitor or a desktop rectangle spanning several monitors, but desktop permissions, display scaling, coordinate origins, and headless execution determine whether it succeeds.

What the Java screenshot API actually captures

Oracle describes Robot.createScreenCapture(Rectangle) as creating an image containing pixels read from the screen. It captures the rendered desktop, not a browser page or a Java component. The rectangle’s x, y, width, and height are measured in the operating system’s screen-coordinate space.

A rectangle with a positive size is required. A zero-sized rectangle, a rectangle built from the wrong coordinate system, or a display that disappeared can cause an exception or an unusable result. Keep capture work off Swing’s or AWT’s event-dispatch thread: reading screen pixels can take noticeable time, and an operating-system permission prompt may require user interaction.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
  • WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
  • A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents

Capture the primary display

The minimal example above uses Toolkit.getDefaultToolkit().getScreenSize(). That size represents the default (normally primary) display. Compile and run it on an interactive desktop:

  1. Save the file as FullScreenShot.java.
  2. Compile with javac FullScreenShot.java.
  3. Run with java FullScreenShot.
  4. Open screenshot.png from the directory in which the command was run.

ImageIO.write returns a boolean indicating whether a writer was found for the requested format. PNG is provided by standard Java runtimes and preserves sharp text without lossy compression. To use JPEG, change the format string to "jpg" and the filename accordingly; JPEG is smaller for photographic content but introduces compression artifacts around text and UI edges.

Capture a known region instead of the whole display

Pass an explicit screen-coordinate rectangle when you need only part of a display:

Rectangle area = new Rectangle(100, 100, 1200, 800);
BufferedImage image = new Robot().createScreenCapture(area);
ImageIO.write(image, "png", new File("region.png"));

Coordinates can be negative when a monitor is positioned to the left or above another monitor. Do not assume that every display begins at (0, 0).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Capture one selected monitor

For a particular physical display, obtain its GraphicsDevice, construct the Robot for that device, and capture that device’s configuration bounds. This avoids confusing a monitor’s local size with its location in the virtual desktop.

Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
  • 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
  • SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
  • INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
  • THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;

public class MonitorShot {
    public static void main(String[] args) throws Exception {
        GraphicsEnvironment environment =
                GraphicsEnvironment.getLocalGraphicsEnvironment();
        GraphicsDevice[] devices = environment.getScreenDevices();

        if (devices.length == 0) {
            throw new IllegalStateException("No display device is available");
        }

        int monitorIndex = 0; // Change this after enumerating devices.
        GraphicsDevice device = devices[monitorIndex];
        GraphicsConfiguration configuration = device.getDefaultConfiguration();
        Rectangle bounds = configuration.getBounds();

        BufferedImage image = new Robot(device).createScreenCapture(bounds);
        ImageIO.write(image, "png", new File("monitor-" + monitorIndex + ".png"));
    }
}

Device ordering is supplied by the platform and is not a guaranteed physical left-to-right order. If a user must choose a monitor, list each device’s identifier and configuration bounds, then let the user select the desired entry rather than hard-coding an index.

Capture the entire virtual desktop across monitors

Build the union of every display configuration’s bounds. The union preserves negative origins and gaps in the desktop layout. Oracle notes that monitors may share a virtual coordinate system or use independent coordinate systems, so inspect and test the coordinate arrangement on the deployment platform.

import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;

public class AllMonitorsShot {
    public static void main(String[] args) throws Exception {
        GraphicsEnvironment ge =
                GraphicsEnvironment.getLocalGraphicsEnvironment();
        Rectangle desktop = null;

        for (GraphicsDevice device : ge.getScreenDevices()) {
            for (GraphicsConfiguration gc : device.getConfigurations()) {
                Rectangle bounds = gc.getBounds();
                desktop = desktop == null
                        ? new Rectangle(bounds)
                        : desktop.union(bounds);
            }
        }

        if (desktop == null || desktop.width <= 0 || desktop.height <= 0) {
            throw new IllegalStateException("No usable display bounds found");
        }

        BufferedImage image = new Robot().createScreenCapture(desktop);
        ImageIO.write(image, "png", new File("desktop.png"));
    }
}

The output includes the rectangular area between monitors. If the screens are arranged with a gap or an L-shaped layout, those unused pixels appear as the platform’s desktop background. That is expected: one image must represent the union’s bounding rectangle. If you need separate files with no gaps, capture each configuration independently and save one image per display.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

High-DPI and multi-resolution captures

On a scaled display, logical user dimensions and native device pixels differ. When your application needs both representations, use createMultiResolutionScreenCapture(Rectangle). It returns a MultiResolutionImage; on a scaled display it can provide a user-size base image and a native device-resolution variant. On an unscaled display, there is one variant.

import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.awt.image.MultiResolutionImage;
import java.util.List;

Robot robot = new Robot();
MultiResolutionImage multi =
        robot.createMultiResolutionScreenCapture(new Rectangle(0, 0, 1400, 900));
List<BufferedImage> variants = multi.getResolutionVariants();
for (int i = 0; i < variants.size(); i++) {
    BufferedImage variant = variants.get(i);
    System.out.println(i + ": " + variant.getWidth() + "x" + variant.getHeight());
}

Choose the variant deliberately: a native-resolution image is useful for pixel-accurate archival or computer-vision work, while the base image usually matches the dimensions a user sees. Re-check bounds after a scale-factor or monitor change.

Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
  • Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
  • Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
  • In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
  • Ultra-thin bezels: Maximize your viewing experience with thin bezels.

Run capture safely in a desktop application

Do not block the AWT event-dispatch thread. A simple background task can capture and then notify the UI:

import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
    try {
        BufferedImage image = new Robot().createScreenCapture(
                new Rectangle(0, 0, 1280, 720));
        ImageIO.write(image, "png", new File("background-shot.png"));
        System.out.println("Saved background-shot.png");
    } catch (Exception e) {
        e.printStackTrace();
    }
});

Shut down the executor when the application exits. For repeated captures, reuse a Robot while the display topology remains stable, but recreate it and recompute bounds after monitors are unplugged, reordered, or their scaling changes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why capture fails (and how to fix it)

AWTException at new Robot()

This normally means the process is headless or the platform disallows low-level input/screen control. Confirm that Java is running inside a real interactive desktop session. A Linux service, container, CI runner, or SSH session without an attached display needs a different architecture, such as a properly configured virtual display, rather than a change to the image format.

HeadlessException or a display lookup failure

Check the runtime environment before creating GUI objects:

import java.awt.GraphicsEnvironment;

if (GraphicsEnvironment.isHeadless()) {
    throw new IllegalStateException("Screen capture requires an attached display");
}

Do not try to “fix” this by setting a fake headless flag: headless mode intentionally has no pixels to read.

Rank #4
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
  • SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
  • MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
  • KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
  • INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient

SecurityException, black images, or undefined pixels

The operating system may deny screen recording. Oracle warns that createScreenCapture can throw SecurityException when access is denied and that returned pixels may be undefined without required permission. On macOS, grant the launching application (for example, Terminal, an IDE, or the packaged app) Screen Recording permission in System Settings, then restart it. On other platforms, check the desktop’s privacy or screen-capture policy and whether the process runs in the same logged-in session as the display.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Image has the wrong size or a missing monitor

Log every GraphicsConfiguration.getBounds() value before capturing. A negative origin is valid. Recompute the union after display changes, and reject rectangles whose width or height is not positive. For mixed-DPI setups, compare the ordinary and multi-resolution APIs rather than multiplying dimensions by an assumed scale factor.

The application freezes while taking a shot

Move capture and file encoding to a worker thread. PNG encoding can also be expensive for a very large multi-monitor image. If latency matters, capture a smaller region, choose JPEG where its artifacts are acceptable, or encode asynchronously after the pixels have been read.

Operational and security considerations

  • Memory: a screenshot uses approximately width × height × four bytes before encoding, with additional encoder overhead. A large, high-DPI desktop can therefore require hundreds of megabytes.
  • Privacy: the image may contain passwords, notifications, customer data, or other windows. Restrict output permissions, encrypt it in transit and at rest, and delete temporary files on a defined schedule.
  • Consistency: windows can move while the capture occurs. If you need a stable state, pause the workflow or coordinate capture with the application being observed.
  • Format: PNG is lossless and broadly supported; JPEG is smaller but lossy. Use a filename extension that matches the format you pass to ImageIO.write.
  • Deployment: desktop Robot capture is interactive by design. A server-side page-rendering service is usually a better fit when no user desktop is available.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is a website image rather than the pixels of the user’s desktop, a screenshot API avoids Java GUI dependencies, display permissions, and virtual monitors. ScreenshotNeo returns PNG, JPEG, WebP, or PDF from one request. Before capture it accepts cookie/consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing result.

Use the API documentation at https://screenshotneo.com/docs/ for the full option set. A minimal cURL request is:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

Python:

import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)

Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const fs = await import('node:fs/promises');
await fs.writeFile('shot.webp', Buffer.from(await res.arrayBuffer()));

ScreenshotNeo also supports full-page captures with lazy images loaded, CSS-selector element captures, dark mode, 12 device presets or custom viewports, retina scale, PDF paper and page controls, HTML/CSS input, custom JavaScript and CSS, pre-capture clicks, hidden selectors, waits for selectors, delays or network idle, ad/tracker/request/resource blocking, headers, cookies, user agents, Authorization, timezone, geolocation, transparent backgrounds, resizing, chosen cache TTLs, signed links, asynchronous jobs with signed webhooks, up to 100 URLs per bulk call, a usage API, and an OpenAPI specification. Existing parameter names used by other screenshot APIs are accepted to ease migration. An MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
  • 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
  • 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.

The free plan includes 1,000 shots each month with no card. Paid plans start at $5 for 3,000 shots; yearly billing provides two months free, and every feature is available on every plan. Create a free ScreenshotNeo account to try it.

Frequently Asked Questions

Can Java capture a screenshot on a headless server?

Not with an ordinary attached-screen Robot capture. Headless environments have no desktop pixels; use an attached or virtual display, or a server-side rendering/screenshot service instead.

Why are my multi-monitor coordinates negative?

Operating systems commonly place a monitor left of or above the primary display, so its virtual-desktop origin can be negative. Use each GraphicsConfiguration’s bounds rather than assuming (0, 0).

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should I use createMultiResolutionScreenCapture for every screenshot?

Use it when scaled-display resolution variants matter. For ordinary single-resolution output, createScreenCapture is simpler.

Does Robot capture only the Java window?

No. Robot reads pixels from the screen rectangle you provide, including other applications and the desktop.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.