Java获取系统分辨率的方法及步骤详解?
- 后端开发
- 2025-10-16
- 6
在Java中获取系统分辨率可以通过使用GraphicsEnvironment类和GraphicsConfiguration接口来实现,以下是一个详细的步骤和示例代码,展示如何获取系统的分辨率。

步骤分析
- 获取GraphicsEnvironment实例:使用GraphicsEnvironment.getLocalGraphicsEnvironment()方法获取本地环境的GraphicsEnvironment实例。
- 获取所有显示配置:通过调用GraphicsEnvironment实例的getScreenDevices()方法获取所有屏幕的GraphicsDevice数组。
- 遍历显示配置:遍历每个GraphicsDevice,获取其GraphicsConfiguration。
- 获取分辨率:通过调用GraphicsConfiguration的getBounds()方法获取分辨率。
示例代码
import java.awt.GraphicsConfiguration; import java.awt.GraphicsDevice; import java.awt.GraphicsEnvironment; import java.awt.Rectangle; public class SystemResolution { public static void main(String[] args) { // 获取本地环境的GraphicsEnvironment实例 GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); // 获取所有屏幕的GraphicsDevice数组 GraphicsDevice[] screens = ge.getScreenDevices(); // 遍历每个屏幕 for (GraphicsDevice screen : screens) { // 获取屏幕的GraphicsConfiguration GraphicsConfiguration config = screen.getDefaultConfiguration(); // 获取分辨率 Rectangle bounds = config.getBounds(); int width = bounds.width; int height = bounds.height; // 输出分辨率 System.out.println("Screen: " + screen.getIDstring()); System.out.println("Resolution: " + width + "x" + height); System.out.println(); } } }
表格展示
| 屏幕ID | 分辨率 |
|---|---|
| Screen 0 | 1920×1080 |
| Screen 1 | 1280×720 |
FAQs
Q1:如何获取单个屏幕的分辨率?
A1: 如果只想获取单个屏幕的分辨率,可以通过GraphicsDevice的getDefaultConfiguration()方法获取默认的GraphicsConfiguration,然后使用getBounds()方法获取分辨率。


GraphicsDevice screen = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice(); GraphicsConfiguration config = screen.getDefaultConfiguration(); Rectangle bounds = config.getBounds(); int width = bounds.width; int height = bounds.height; System.out.println("Resolution: " + width + "x" + height);
Q2:如何获取所有屏幕的总分辨率?
A2: 如果需要获取所有屏幕的总分辨率,可以将每个屏幕的分辨率相加,以下是一个示例代码:
int totalWidth = 0; int totalHeight = 0; for (GraphicsDevice screen : screens) { GraphicsConfiguration config = screen.getDefaultConfiguration(); Rectangle bounds = config.getBounds(); totalWidth += bounds.width; totalHeight += bounds.height; } System.out.println("Total Resolution: " + totalWidth + "x" + totalHeight);