A common Java/Swing question is, "How do I determine the screen resolution (or screen size)?"
Answer: You can determine the screen resolution (screen size) using the Toolkit class. This method call returns the screen resolution in pixels, and stores the results in a Dimension object, as shown here:
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
You can then get the screen width and height as int
's by directly accessing the width
and height
fields of the Dimension
class, like this:
screenHeight = screenSize.height; screenWidth = screenSize.width;
I thought I better mention that, because it's a little unusual to access fields directly like this (there are typically "get" methods for accessing variables). Interestingly, Dimension
class does have methods named getWidth
and getHeight
, and they return the type double
.
Setting the size of a JFrame
While I'm in the neighborhood of screen dimensions, I thought I'd mention that once you have the screen dimensions, you can easily set the JFrame size to half the height and half the width of the screen, like this:
frame.setSize(screenWidth / 2, screenHeight / 2);
Nothing sensational here, but I thought I'd mention this, as it is something I do for most Swing applications (at least those where I don't bother to remember the last user-specific height and width settings).