When my program starts, the main window places itself where it was when it was last closed. I want to modify this behavior some so if the window is off-screen (or partially off-screen) it moves itself to fully on screen.
I’ve got this working perfectly. Here’s the code:
int x = gameConfig.windowX; int y = gameConfig.windowY; int width = gameConfig.windowWidth; int height = gameConfig.windowHeight; if( x < 0 ) x = 0; if( y < 0 ) y = 0; Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); if( x + width > screenSize.width ) x = screenSize.width - width; if( y + height > screenSize.height ) y = screenSize.height - height; if( width > screenSize.width ) width = screenSize.width; if( height > screenSize.height ) height = screenSize.height; this.setLocation(x, y); this.setSize(width, height ); if( gameConfig.screenMaximized ) { this.setExtendedState(getExtendedState() | MAXIMIZED_BOTH ); }
This works as expected, but with one big exception; it doesn’t account for taskbars. On windows, if the window is past the bottom of the screen, this code will correct it, but it still leaves a piece of the window blocked by the taskbar.
I’m not sure how to do this. Is there someway to ask java about any taskbars in the system, and what their width/height is?
Thanks that worked perfectly.
Do you know how to get it so Java will reflect the total screen size of both of my monitors when I call getScreenSize() ? Right now it is returning 1600×1200, when it’s really 3200×1200, spanned across two monitors.
The Java API suggests that GraphicsConfiguration.getBounds() would do the trick, but that still returns the rectangle {0, 0, 1600, 1200}.
Use getScreenInsets (Java 4+):
(This method allows for multiple screens, and older JVM’s that don’t support the API).
And, always remember the task bar may be on any edge of the screen, not just the bottom.