Java로 화면 해상도를 얻으려면 어떻게해야합니까?


136

화면 해상도 (폭 x 높이)를 어떻게 픽셀 단위로 얻을 수 있습니까?

JFrame과 Java 스윙 메소드를 사용하고 있습니다.


2
하나의 라이너는 수백 가지 방법으로 이어질 수 있습니다.
— Anil Vishnoi

7
여러 모니터 설정에 신경 쓰지 않는 것 같습니다. 많은 응용 프로그램 개발자가이를 무시하는 것 같습니다. 모두 내가 일하는 곳에서 여러 대의 모니터를 사용하므로 항상 생각해야합니다. 모든 모니터를 프로빙하고 스크린 객체로 설정하여 새 프레임을 열 때 대상을 지정할 수 있습니다. 이 기능이 실제로 필요하지 않으면 개방형 질문을하고 너무 빨리 답변을 받아도 괜찮습니다.
— Erick Robertson

답변:


267

이 Toolkit.getScreenSize()방법으로 화면 크기를 얻을 수 있습니다 .

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();

다중 모니터 구성에서는 다음을 사용해야합니다.

GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
int width = gd.getDisplayMode().getWidth();
int height = gd.getDisplayMode().getHeight();

DPI로 화면 해상도를 얻으려면의 getScreenResolution()방법 을 사용해야합니다 Toolkit.


자료 :


4
이것은 나를 위해 작동하지 않습니다. 3840x2160 모니터가 있지만 getScreenSize1920x1080을 반환합니다.
— ZhekaKozlov

15

이 코드는 시스템의 그래픽 장치를 열거하고 (여러 모니터가 설치된 경우) 해당 정보를 사용하여 모니터 선호도 또는 자동 배치를 결정할 수 있습니다 (일부 시스템은 앱이 실행되는 동안 실시간 디스플레이를 위해 작은 모니터를 사용함) 배경 및 이러한 모니터는 크기, 화면 색상 등으로 식별 할 수 있습니다.) :

// Test if each monitor will support my app's window
// Iterate through each monitor and see what size each is
GraphicsEnvironment ge      = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[]    gs      = ge.getScreenDevices();
Dimension           mySize  = new Dimension(myWidth, myHeight);
Dimension           maxSize = new Dimension(minRequiredWidth, minRequiredHeight);
for (int i = 0; i < gs.length; i++)
{
    DisplayMode dm = gs[i].getDisplayMode();
    if (dm.getWidth() > maxSize.getWidth() && dm.getHeight() > maxSize.getHeight())
    {   // Update the max size found on this monitor
        maxSize.setSize(dm.getWidth(), dm.getHeight());
    }

    // Do test if it will work here
}


3

주어진 구성 요소가 현재 지정된 화면의 해상도입니다 (루트 창의 대부분이 해당 화면에 표시됨).

public Rectangle getCurrentScreenBounds(Component component) {
    return component.getGraphicsConfiguration().getBounds();
}

용법:

Rectangle currentScreen = getCurrentScreenBounds(frameOrWhateverComponent);
int currentScreenWidth = currentScreen.width // current screen width
int currentScreenHeight = currentScreen.height // current screen height
// absolute coordinate of current screen > 0 if left of this screen are further screens
int xOfCurrentScreen = currentScreen.x

툴바 등을 존중하려면 다음과 같이 계산해야합니다.

GraphicsConfiguration gc = component.getGraphicsConfiguration();
Insets screenInsets = Toolkit.getDefaultToolkit().getScreenInsets(gc);

3

다음은 가장 오른쪽 화면의 가장 오른쪽 가장자리의 x 위치를 반환하는 일부 기능 코드 (Java 8)입니다. 화면이 없으면 0을 반환합니다.

  GraphicsDevice devices[];

  devices = GraphicsEnvironment.
     getLocalGraphicsEnvironment().
     getScreenDevices();

  return Stream.
     of(devices).
     map(GraphicsDevice::getDefaultConfiguration).
     map(GraphicsConfiguration::getBounds).
     mapToInt(bounds -> bounds.x + bounds.width).
     max().
     orElse(0);

다음은 JavaDoc에 대한 링크입니다.

GraphicsEnvironment.getLocalGraphicsEnvironment ()
GraphicsEnvironment.getScreenDevices ()
GraphicsDevice.getDefaultConfiguration ()
GraphicsConfiguration.getBounds ()


2

이 세 함수는 화면 크기를 Java로 반환합니다. 이 코드는 다중 모니터 설정 및 작업 표시 줄을 설명합니다. 포함 된 함수는 getScreenInsets () , getScreenWorkingArea () 및 getScreenTotalArea () 입니다.

암호:

/**
 * getScreenInsets, This returns the insets of the screen, which are defined by any task bars
 * that have been set up by the user. This function accounts for multi-monitor setups. If a
 * window is supplied, then the the monitor that contains the window will be used. If a window
 * is not supplied, then the primary monitor will be used.
 */
static public Insets getScreenInsets(Window windowOrNull) {
    Insets insets;
    if (windowOrNull == null) {
        insets = Toolkit.getDefaultToolkit().getScreenInsets(GraphicsEnvironment
                .getLocalGraphicsEnvironment().getDefaultScreenDevice()
                .getDefaultConfiguration());
    } else {
        insets = windowOrNull.getToolkit().getScreenInsets(
                windowOrNull.getGraphicsConfiguration());
    }
    return insets;
}

/**
 * getScreenWorkingArea, This returns the working area of the screen. (The working area excludes
 * any task bars.) This function accounts for multi-monitor setups. If a window is supplied,
 * then the the monitor that contains the window will be used. If a window is not supplied, then
 * the primary monitor will be used.
 */
static public Rectangle getScreenWorkingArea(Window windowOrNull) {
    Insets insets;
    Rectangle bounds;
    if (windowOrNull == null) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        insets = Toolkit.getDefaultToolkit().getScreenInsets(ge.getDefaultScreenDevice()
                .getDefaultConfiguration());
        bounds = ge.getDefaultScreenDevice().getDefaultConfiguration().getBounds();
    } else {
        GraphicsConfiguration gc = windowOrNull.getGraphicsConfiguration();
        insets = windowOrNull.getToolkit().getScreenInsets(gc);
        bounds = gc.getBounds();
    }
    bounds.x += insets.left;
    bounds.y += insets.top;
    bounds.width -= (insets.left + insets.right);
    bounds.height -= (insets.top + insets.bottom);
    return bounds;
}

/**
 * getScreenTotalArea, This returns the total area of the screen. (The total area includes any
 * task bars.) This function accounts for multi-monitor setups. If a window is supplied, then
 * the the monitor that contains the window will be used. If a window is not supplied, then the
 * primary monitor will be used.
 */
static public Rectangle getScreenTotalArea(Window windowOrNull) {
    Rectangle bounds;
    if (windowOrNull == null) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        bounds = ge.getDefaultScreenDevice().getDefaultConfiguration().getBounds();
    } else {
        GraphicsConfiguration gc = windowOrNull.getGraphicsConfiguration();
        bounds = gc.getBounds();
    }
    return bounds;
}

1
int resolution =Toolkit.getDefaultToolkit().getScreenResolution();

System.out.println(resolution);

1
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();
framemain.setSize((int)width,(int)height);
framemain.setResizable(true);
framemain.setExtendedState(JFrame.MAXIMIZED_BOTH);

1

여기 자주 사용하는 코드가 있습니다. 기본 모니터 위치를 유지하면서 사용 가능한 전체 화면 영역 (멀티 모니터 설정에서도)을 반환합니다.

public static Rectangle getMaximumScreenBounds() {
    int minx=0, miny=0, maxx=0, maxy=0;
    GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
    for(GraphicsDevice device : environment.getScreenDevices()){
        Rectangle bounds = device.getDefaultConfiguration().getBounds();
        minx = Math.min(minx, bounds.x);
        miny = Math.min(miny, bounds.y);
        maxx = Math.max(maxx,  bounds.x+bounds.width);
        maxy = Math.max(maxy, bounds.y+bounds.height);
    }
    return new Rectangle(minx, miny, maxx-minx, maxy-miny);
}

풀 HD 모니터가 2 개인 컴퓨터에서 왼쪽 모니터가 기본 모니터로 설정되어있는 경우 (Windows 설정에서)이 함수는

java.awt.Rectangle[x=0,y=0,width=3840,height=1080]

동일한 설정에서 올바른 모니터를 기본 모니터로 설정하면이 함수는

java.awt.Rectangle[x=-1920,y=0,width=3840,height=1080]

0
int screenResolution = Toolkit.getDefaultToolkit().getScreenResolution();
System.out.println(""+screenResolution);

스택 오버플로에 오신 것을 환영합니다! 이 코드 스 니펫은 문제를 해결할 수 있지만 설명을 포함하면 게시물의 품질을 향상시키는 데 실제로 도움이됩니다. 앞으로 독자들에게 질문에 대한 답변을 제공하므로 해당 사람들이 코드 제안의 이유를 모를 수도 있습니다. 설명 주석으로 코드를 복잡하게 만들지 마십시오. 이렇게하면 코드와 설명의 가독성이 떨어집니다!
— kayess
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.