hi guys, am stil new to java their was a snippest code about getting screen size i've being seeing onine calling window.getSize() in what package is the object located.

// Get the size of the screen
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

// Determine the new location of the window
int w = window.getSize().width;                //what package is window.getSize() from?
int h = window.getSize().height;                //what package is window.getSize() from?
int x = (dim.width-w)/2;
int y = (dim.height-h)/2;

// Move the window
window.setLocation(x, y);

it will be helpful if someone can say something

5 Years
Discussion Span
Last Post by hakeemtunde

window is a variable. From the context I guess its a top-level Swing component (JFrame, JDialog, JApplet...)
getSize() is a method that's available for all Swing components. Top-level components inherit it from java.awt.Component. Others inherit it from javax.swing.JComponent.

ps *window.setLocationRelativeTo(null); * does the same thing as that code, but in one line, and it handles multi-screen configurations sensibly.

Edited by JamesCherrill


Ok. If am to write that code how do i go about it. I mean can you write the code for me so as for me to know is propery instantiated and used in context of the above code


It assumes yo have a JFrame or whatever called window. Then when you run the code it moves your window to the centre of the screen. That's all. If your window is called something else, use that name instead of window. You just put the code somewhere in one of your methods, whenever you want the screen to be centered.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.