web-dev-qa-db-fra.com

Comment puis-je obtenir une résolution d'écran en java?

Comment obtenir la résolution de l'écran (largeur x hauteur) en pixels?

J'utilise un JFrame et les méthodes Java swing.

126
AndreDurao

Vous pouvez obtenir la taille de l'écran avec la méthode Toolkit.getScreenSize().

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

Sur une configuration multi-moniteurs, vous devriez utiliser ceci:

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

Si vous souhaitez obtenir la résolution de l'écran en DPI, vous devez utiliser la méthode getScreenResolution() sur Toolkit.


Ressources:

249
Colin Hebert

Ce code énumère les périphériques graphiques du système (si plusieurs moniteurs sont installés) et vous pouvez utiliser ces informations pour déterminer l'affinité ou le placement automatique du moniteur (certains systèmes utilisent un petit moniteur latéral pour les affichages en temps réel lorsqu'une application est en cours d'exécution dans. l’arrière-plan, et un tel moniteur peut être identifié par sa taille, ses couleurs, etc.):

// 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
}
15
Rick Hodgin

Cet appel vous donnera les informations que vous souhaitez.

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
11
Starkey

Il s’agit de la résolution de l’écran auquel le composant donné est actuellement affecté (une partie semblable à la majeure partie de la fenêtre racine est visible sur cet écran).

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

Usage:

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

Si vous voulez respecter les barres d’outils, etc., vous devrez aussi calculer avec ceci:

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

Voici un code fonctionnel (Java 8) qui renvoie la position x du bord le plus à droite de l'écran le plus à droite. Si aucun écran n'est trouvé, il renvoie 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);

Voici des liens vers le JavaDoc.

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

3
Nathan

Ces trois fonctions renvoient la taille de l'écran en Java. Ce code explique les configurations multi-moniteurs et les barres de tâches. Les fonctions incluses sont les suivantes: getScreenInsets (), getScreenWorkingArea (), et getScreenTotalArea ().

Code:

/**
 * 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
BlakeTNC

Voici un extrait de code que j'utilise souvent. Il renvoie la totalité de la zone d'écran disponible (même sur les configurations à plusieurs moniteurs) tout en conservant les positions natives du moniteur.

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

Sur un ordinateur équipé de deux moniteurs Full HD, où le moniteur gauche est défini comme moniteur principal (dans les paramètres Windows), la fonction renvoie

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

Sur la même configuration, mais avec le moniteur de droite défini comme moniteur principal, la fonction retourne

Java.awt.Rectangle[x=-1920,y=0,width=3840,height=1080]
1
Myrka
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
Ajeeth Kumar
int resolution =Toolkit.getDefaultToolkit().getScreenResolution();

System.out.println(resolution);
1
Eric Warriner
int screenResolution = Toolkit.getDefaultToolkit().getScreenResolution();
System.out.println(""+screenResolution);
0
chamindu ilshan