2009-12-20 20 views
40

¿Alguien sabe cómo obtendría el ancho de la pantalla en java? Leí algo sobre algún método de toolkit, pero no estoy muy seguro de qué es eso.¿Cómo se obtiene el ancho de la pantalla en java?

Gracias, Andrew

+5

Nota, un cuidado especial debe ser tomado al tener varios monitores. –

+1

También DEBE tener en cuenta las inserciones de pantalla (ver mi respuesta); a muchas personas les gusta mover la barra de tareas a uno u otro lado de la pantalla. –

Respuesta

77
java.awt.Toolkit.getDefaultToolkit().getScreenSize() 
+0

McCan: regresa? – Hydroid

+1

@Hydroid http://stackoverflow.com/a/8101318/632951 – Pacerier

+0

Devuelve un objeto del tipo 'Dimension' – KJaeg

5

El siguiente código debe hacerlo (no lo he probado):

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); 
GraphicsDevice gd = ge.getDefaultScreenDevice(); 
gd.getDefaultConfiguration().getBounds().getWidth(); 

edición:

para múltiples monitores que debe utilizar el siguiente código (tomado de javadoc of java.awt.GraphicsConfiguration:

Rectangle virtualBounds = new Rectangle(); 
    GraphicsEnvironment ge = GraphicsEnvironment. 
      getLocalGraphicsEnvironment(); 
    GraphicsDevice[] gs = 
      ge.getScreenDevices(); 
    for (int j = 0; j < gs.length; j++) { 
     GraphicsDevice gd = gs[j]; 
     GraphicsConfiguration[] gc = 
      gd.getConfigurations(); 
     for (int i=0; i < gc.length; i++) { 
      virtualBounds = 
       virtualBounds.union(gc[i].getBounds()); 
     } 
    } 
+0

Nice grab. He estado buscando esto por días, simplemente no pude encontrar los criterios de búsqueda correctos en SO. –

2

El PO probablemente quería algo como esto:

Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); 
1
Toolkit.getDefaultToolkit().getScreenSize().getWidth() 
5

Toolkit tiene un número de clases que ayudaría:

  1. getScreenSize - pantalla prima tamaño
  2. getScreenInsets - obtiene el tamaño de la barra de herramientas , Muelle
  3. getScreenResolution - dpi

Nosotros las usamos 1 y 2, para calcular el tamaño de ventana máximo utilizable. Para obtener la configuración de gráficos pertinente, utilizamos

GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0].getDefaultConfiguration(); 

pero puede haber soluciones más inteligentes de monitores múltiples.

+0

es el primer elemento de la matriz 'getScreenDevices' ** garantizado ** para ser el monitor principal? – Pacerier

+0

No especificado en la API; mejor ir con getDefaultScreenDevice? http://download.oracle.com/javase/6/docs/api/java/awt/GraphicsEnvironment.html#getDefaultScreenDevice() –

+0

¿Quiere decir 'GraphicsEnvironment.getDefaultScreenDevice()'? – Pacerier

18

Estos son los dos métodos que uso, que representan múltiples monitores e insertos de barras de tareas. Si no necesita los dos métodos por separado, puede, por supuesto, evitar obtener la configuración de gráficos dos veces.

static public Rectangle getScreenBounds(Window wnd) { 
    Rectangle       sb; 
    Insets        si=getScreenInsets(wnd); 

    if(wnd==null) { 
     sb=GraphicsEnvironment 
      .getLocalGraphicsEnvironment() 
      .getDefaultScreenDevice() 
      .getDefaultConfiguration() 
      .getBounds(); 
     } 
    else { 
     sb=wnd 
      .getGraphicsConfiguration() 
      .getBounds(); 
     } 

    sb.x  +=si.left; 
    sb.y  +=si.top; 
    sb.width -=si.left+si.right; 
    sb.height-=si.top+si.bottom; 
    return sb; 
    } 

static public Insets getScreenInsets(Window wnd) { 
    Insets        si; 

    if(wnd==null) { 
     si=Toolkit.getDefaultToolkit().getScreenInsets(GraphicsEnvironment 
      .getLocalGraphicsEnvironment() 
      .getDefaultScreenDevice() 
      .getDefaultConfiguration()); 
     } 
    else { 
     si=wnd.getToolkit().getScreenInsets(wnd.getGraphicsConfiguration()); 
     } 
    return si; 
    } 
+0

+1 para mostrar cómo agarrar las inserciones. Pueden ser importantes, especialmente en OS X, si desea tener una ventana de tamaño completo sin superponerse al dock. –

+0

@SoftwareMonkey está ahí para obtener la configuración de gráficos sin tener que crear un nuevo Marco? – Pacerier

+0

-1: no hay 'Toolkit.getDefaultToolkit(). GetGraphicsConfiguration()' – jan

16

El área de trabajo es el área del escritorio de la pantalla, con exclusión de las barras de tareas, ventanas acopladas, y barras de herramientas acopladas.

Si lo que quiere es el "área de trabajo" de la pantalla, utilice la siguiente:

public static int GetScreenWorkingWidth() { 
    return java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().width; 
} 

public static int GetScreenWorkingHeight() { 
    return java.awt.GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds().height; 
} 
+1

esto no funciona para situaciones de monitores múltiples – jan

0

Si necesita la resolución de la pantalla que un cierto componente está actualmente asignado a (algo así como la mayor parte de la ventana raíz es visible en esa pantalla), puede usar this answer.

0

Una buena manera de detectar si algo es o no dentro de los límites visuales, está utilizando

Screen.getScreensForRectangle(x, y, width, height).isEmpty(); 
0

Ésta es una mejora a la solución multi-monitor publicado (arriba) por Lawrence Dol. Como en su solución, este código representa múltiples monitores e insertos de barra de tareas. Las funciones incluidas son: getScreenInsets(), getScreenWorkingArea() y getScreenTotalArea().

cambios de la versión Lawrence Dol:

  • Esto evita conseguir la configuración de gráficos en dos ocasiones.
  • Se agregó una función para obtener el área total de la pantalla.
  • Cambié el nombre de las variables para mayor claridad.
  • Javadocs añadidos.

Código:

/** 
* 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; 
} 
Cuestiones relacionadas