Reputation: 11
I have working with swing API for the first time to get the screen resolution for my win application.
How to set present screensize in Java Swing?
Upvotes: 1
Views: 302
Reputation: 347204
The question depends. Do you want the full screen size or the usable screen size (minus things like the taskbar and the dock)? Do you want the default screen or a specific screen?
First you need to grab a reference to the current GraphicsEnvironment
...
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
Then you can grab a list of the GraphicsDevice
s available on the system...
GraphicsDevice lstGDs[] = ge.getScreenDevices();
Or if you just want the current/default screen, you can use...
GraphicsDevice device = ge.getDefaultScreenDevice();
Anyway, which ever you choose, next, you need to get the GraphicsConfiguration
from the device...
GraphicsConfiguration cf = device.getDefaultConfiguration();
And finally, you can grab the screen bounds, this includes the position and size of the screen within the virtual desktop...
Rectangle bounds = cf.getBounds();
This takes into consideration things like the task bar or dock or other UI elements the OS might have on the screen, which you shouldn't try and appear over/behind. Not everybody has these at the bottom of the screen ;)
Start by grabbing your GraphicsConfiguration
from your selected GraphicsDevice
, from this, get the screen bounds...
GraphicsDevice device = ge.getDefaultScreenDevice(); // or what ever device you want...
GraphicsConfiguration cf = device.getDefaultConfiguration();
Rectangle bounds = cf.getBounds();
Next, get the screen insets...
Insets insets = Toolkit.getDefaultToolkit().getScreenInsets(gc);
This represents the area taken up by the OS to display its extra stuff. Now, reduce the screen bounds by the insets...
bounds.x += insets.left;
bounds.y += insets.top;
bounds.width -= (insets.left + insets.right);
bounds.height -= (insets.top + insets.bottom);
This represents the safe/viewable area you window can appear in without been blocked by this other elements...
Or you could just use JFrame#setExtendState
and pass it JFrame.MAXIMIZED_BOTH
which will take care of it all for you...
Upvotes: 2
Reputation: 3990
Try this
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int height = screenSize.height;
int width = screenSize.width;
//set size to the JFrame
this.setSize(width,height);
Upvotes: 0
Reputation: 2578
Use
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
double width = dimension .getWidth();
double height = imension .getHeight();
For your JFrame use setSize(Dimension dimension)
to set size
Upvotes: 0