Does anyone know how you would get the screen width in java? I read something about some toolkit method but I'm not quite sure what that is.
Thanks, Andrew
Does anyone know how you would get the screen width in java? I read something about some toolkit method but I'm not quite sure what that is.
Thanks, Andrew
The following code should do it (haven't tried it):
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
gd.getDefaultConfiguration().getBounds().getWidth();
edit:
For multiple monitors you should use the following code (taken from the 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());
}
}
They probably meant somethinglike this:
Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
Toolkit has a number of classes that would help:
We end up using 1 and 2, to compute usable maximum window size. To get the relevant GraphicsConfiguration, we use
GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()[0].getDefaultConfiguration();
but there may be smarter multiple-monitor solutions.
Here are the two methods I use, which account for multiple monitors and task-bar insets. If you don't need the two method separate, you can, of course, avoid getting the graphics config twice.
static public Rectangle getScreenBounds(Window wnd) {
Rectangle sb;
Insets si=getScreenInsets(wnd);
if(wnd==null) { sb=Toolkit.getDefaultToolkit().getGraphicsConfiguration().getBounds(); }
else { sb=wnd .getGraphicsConfiguration().getBounds(); }
sb.x +=si.left;
sb.width -=(si.left+si.right);
sb.y +=si.top;
sb.height-=(si.top+si.bottom);
return sb;
}
static public Insets getScreenInsets(Window wnd) {
Insets si;
if(wnd==null) { si=Toolkit.getDefaultToolkit().getScreenInsets(new Frame().getGraphicsConfiguration()); }
else { si=wnd.getToolkit() .getScreenInsets(wnd.getGraphicsConfiguration()); }
return si;
}