Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.
Use java.awt.Robot with a java.awt.Rectangle. The rectangle’s x and y are screen coordinates, and its positive width and height define the region. Robot.createScreenCapture(area) returns a BufferedImage; save it with ImageIO.write, usually as PNG for sharp interface text.
Capture a rectangular region with Robot
This complete program captures the rectangle whose top-left corner is (100, 80), measures 640 by 360 pixels, and writes region.png in the current working directory.
import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class RegionScreenshot {
public static void main(String[] args) {
int x = 100;
int y = 80;
int width = 640;
int height = 360;
if (width <= 0 || height <= 0) {
throw new IllegalArgumentException("width and height must be greater than zero");
}
Rectangle area = new Rectangle(x, y, width, height);
try {
Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(area);
boolean written = ImageIO.write(image, "png", new File("region.png"));
if (!written) {
throw new IOException("No image writer found for PNG");
}
System.out.println("Saved region.png");
} catch (AWTException | IOException | SecurityException ex) {
ex.printStackTrace();
}
}
}
Compile and run it with a desktop session available:
Outdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchPC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11javac RegionScreenshot.java
java RegionScreenshot
createScreenCapture reads the pixels in the supplied rectangle. It does not capture the mouse pointer. The call can take time, particularly when the operating system must ask for screen-capture permission, so treat it as blocking work rather than an instantaneous UI operation.
#1 Best Overall
- 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
Choose the rectangle correctly
Use screen coordinates, not component coordinates
The rectangle is expressed in the desktop’s coordinate space. In a windowed application, a component’s getX() and getY() are normally relative to its parent, not the physical screen. Convert a component location before constructing the rectangle:
Point screenPoint = component.getLocationOnScreen();
Rectangle area = new Rectangle(
screenPoint.x,
screenPoint.y,
component.getWidth(),
component.getHeight()
);
If you already know the screen location, pass those absolute coordinates directly. On a multi-monitor desktop, the virtual screen can have negative coordinates when a monitor is positioned to the left or above the primary display. Do not force coordinates to start at zero; use the values reported by the desktop or by getLocationOnScreen().
Validate dimensions and boundaries
width and height must both be greater than zero. Validate user-entered values before constructing the rectangle, and reject an accidental zero-sized drag. If a selection can extend beyond a monitor, clamp it to the area your application intends to capture instead of silently producing an unexpected image. A useful selection model stores the drag start and end points, then normalizes them:
Recommended Free Tools
int left = Math.min(startX, endX);
int top = Math.min(startY, endY);
int width = Math.abs(endX - startX);
int height = Math.abs(endY - startY);
Rectangle area = new Rectangle(left, top, width, height);
That normalization lets the user drag in any direction. Add a minimum size if a one-pixel accidental drag is not meaningful.
Rank #2
- 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
Save the captured image
PNG is the usual screenshot format
ImageIO.write(image, "png", file) uses an installed Image I/O writer and returns true when a writer handled the requested format. PNG is generally the safest choice for interface screenshots because it preserves text and lines without lossy compression. Standard Java image writers commonly include PNG, JPEG, GIF, BMP and WBMP; JPEG can be useful for photographic content but may blur small text.
Always check the boolean return value. An IOException can indicate a file-system problem, while a false return means no writer accepted the format. Use an explicit output path when a service or desktop application must place files predictably; a relative path is resolved against the process working directory, which may differ when launched from an IDE or scheduler.
Keep the image in memory when needed
The capture result is already a BufferedImage. You can process, display or pass that object to another part of your program before writing it. If the destination is a file, the pattern above is sufficient; do not recapture merely to change the output format.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Fix the driver behind crashes, sound loss and screen glitches3Repair Windows errors before they cause bigger problemsDo not block Swing’s Event Dispatch Thread
Oracle’s Java SE API recommends avoiding screen capture on the AWT Event Dispatch Thread because capture may be lengthy and permission acquisition can involve user interaction. In a Swing program, perform the capture in a worker and publish the image back to the UI:
Rank #3
- 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.
SwingWorker<BufferedImage, Void> worker = new SwingWorker<>() {
@Override
protected BufferedImage doInBackground() throws Exception {
Robot robot = new Robot();
return robot.createScreenCapture(area);
}
@Override
protected void done() {
try {
BufferedImage image = get();
previewLabel.setIcon(new ImageIcon(image));
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
} catch (ExecutionException ex) {
Throwable cause = ex.getCause();
cause.printStackTrace();
}
}
};
worker.execute();
Import javax.swing.ImageIcon, javax.swing.SwingWorker and the usual concurrency classes in the surrounding application. Keep UI updates in done(), which runs on the event-dispatch thread, and keep the actual capture in doInBackground().
High-DPI displays and multi-resolution capture
For ordinary, non-scaled displays, createScreenCapture(Rectangle) and its BufferedImage result are the simplest option. On a scaled or high-DPI display, Java also provides createMultiResolutionScreenCapture(Rectangle). That method returns a MultiResolutionImage containing a user-sized base image and, when available, a native device-resolution variant.
| Method | Result | Use it when | File-writing consideration |
|---|---|---|---|
createScreenCapture |
BufferedImage |
You need one straightforward image and ordinary display scaling is adequate. | Pass the image directly to ImageIO.write. |
createMultiResolutionScreenCapture |
MultiResolutionImage |
Your application must choose between user-sized and native-resolution variants on a scaled display. | Select the desired resolution variant, then write that rendered image with an Image I/O writer. |
Choose the variant that matches the consumer of the file. A UI preview may prefer the user-sized image, while pixel-accurate export or later processing may require the native-resolution variant. Do not assume that multiplying coordinates by a scale factor is correct; let the multi-resolution API provide the available image variants.
Permissions, desktop sessions and headless execution
Screen-recording permission
Operating systems can require explicit screen-recording or display-capture permission. If permission is missing, Java may throw SecurityException or return undefined contents, depending on the environment and policy. Explain the required permission to users and handle the exception without overwriting an existing screenshot. Permission prompts can make the first call slow, another reason not to run it on the event-dispatch thread.
Rank #4
- 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
Headless environments
A headless server, container or CI job without a usable graphical display cannot construct a usable Robot. Detect that deployment condition before starting a capture workflow and provide a clear error or a different rendering path. A virtual display can make a desktop available in some CI setups, but configuring one is an environment concern rather than a change to the rectangle code.
Security and file handling
Do not let untrusted input choose arbitrary output paths. Resolve a filename inside an approved directory, create the directory if needed, and handle write failures explicitly. Screen images can contain sensitive data; apply the same access controls and retention policy as the rest of your application’s captured content.
Timing, reliability and performance
- Capture only what you need. A smaller rectangle transfers fewer pixels and usually completes faster than a full-desktop capture.
- Wait for the UI state. If another operation has just opened a menu or dialog, schedule the capture after that state is visible rather than assuming repainting is complete.
- Avoid repeated synchronous calls. For a sequence of screenshots, use a worker or executor and keep the UI responsive.
- Manage memory. An image’s raw pixel storage grows with width, height and color depth. Release references to obsolete images and avoid retaining a long sequence in a list unless that is intentional.
- Make failures visible. Distinguish invalid dimensions, permission denial, unavailable display, and file-writing errors so an operator can fix the right layer.
The API itself supplies pixels from the current desktop; it does not pause applications, hide notifications, or remove overlays. If the screen changes during capture, the resulting rectangle reflects what the operating system delivered at that moment.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Repair Windows errors before they cause bigger problemsFix Now →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Troubleshooting common failures
| Symptom | Likely cause | Fix |
|---|---|---|
AWTException: headless environment |
No usable graphical display is available. | Run in a desktop session or configure an appropriate virtual display; do not attempt Robot capture in a truly headless process. |
SecurityException or a blank/undefined image |
Screen-recording permission or a security policy blocked pixel access. | Grant the application’s display-capture permission, restart it if the operating system requires that, and report the failure instead of saving the result. |
| Image is shifted or captures the wrong monitor | Window-relative coordinates were used as screen coordinates, or a monitor has a negative virtual coordinate. | Call getLocationOnScreen(), preserve negative coordinates, and verify the rectangle visually. |
| Exception for an invalid rectangle | Width or height is zero or negative after normalizing a selection. | Reject zero-area drags and validate both dimensions before calling createScreenCapture. |
| File is not created | Parent directory is missing, the process lacks write access, or the format has no writer. | Use a writable absolute directory, create required parents, catch IOException, and check the boolean result from ImageIO.write. |
| Swing window freezes | Capture or file I/O ran on the Event Dispatch Thread. | Move both operations to a worker and update Swing components only when the worker completes. |
| Output looks soft on a high-DPI monitor | The user-sized image was used where native device pixels were required. | Use createMultiResolutionScreenCapture and select the native-resolution variant when the downstream workflow needs it. |
When a web-page screenshot is the real requirement
ScreenshotNeo is a different workflow from Robot: it captures a web page by URL through an API rather than reading your local desktop. Use it when the target is a reproducible webpage image, not a rectangle containing arbitrary pixels from your monitor. It accepts options for full-page captures with lazy images loaded, CSS-selector element capture, dark mode, device presets or custom viewports, retina scale, PDF output, custom CSS and JavaScript, clicks, waits, hidden selectors, blocked requests, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, caching, signed links, asynchronous jobs, webhooks, bulk capture and usage reporting. Its MCP server exposes take_screenshot, get_page_info and capture_pdf to Claude, Cursor and other MCP clients.
Best Value
- 【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.
Or skip the browser setup
For a webpage URL, one request returns an image or PDF. Cookie and consent banners, newsletter popups and chat widgets are removed before the shot. Bot checks, blank pages, failed loads and timeouts are not billed, and response headers identify the page verdict and billing status. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots. See the ScreenshotNeo documentation for all parameters.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
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)
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 data = Buffer.from(await res.arrayBuffer());
await fs.promises.writeFile('shot.webp', data);
Create a free ScreenshotNeo account to get the 1,000 monthly screenshots without adding a card.
Frequently Asked Questions
Does a Robot screenshot include the mouse pointer itself?
No. The screen-capture API returns the pixels in the rectangle but does not include the mouse cursor.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →What should I use when I need a native-resolution image on a scaled display?
Use createMultiResolutionScreenCapture(Rectangle), then select the MultiResolutionImage variant that matches your export or processing requirement.
Quick Recap
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.

