¿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
¿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
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());
}
}
Nice grab. He estado buscando esto por días, simplemente no pude encontrar los criterios de búsqueda correctos en SO. –
Puede obtenerlo utilizando el AWT Toolkit.
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
El PO probablemente quería algo como esto:
Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
Toolkit.getDefaultToolkit().getScreenSize().getWidth()
Toolkit tiene un número de clases que ayudaría:
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.
es el primer elemento de la matriz 'getScreenDevices' ** garantizado ** para ser el monitor principal? – Pacerier
No especificado en la API; mejor ir con getDefaultScreenDevice? http://download.oracle.com/javase/6/docs/api/java/awt/GraphicsEnvironment.html#getDefaultScreenDevice() –
¿Quiere decir 'GraphicsEnvironment.getDefaultScreenDevice()'? – Pacerier
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;
}
+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. –
@SoftwareMonkey está ahí para obtener la configuración de gráficos sin tener que crear un nuevo Marco? – Pacerier
-1: no hay 'Toolkit.getDefaultToolkit(). GetGraphicsConfiguration()' – jan
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;
}
esto no funciona para situaciones de monitores múltiples – jan
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.
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();
É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:
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;
}
Nota, un cuidado especial debe ser tomado al tener varios monitores. –
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. –