To center a window in Java, you can use the setLocationRelativeTo
method of the JFrame
class.
Here is an example of how to center a window:
refer to:lautturi.comJFrame frame = new JFrame("My Window"); frame.setSize(400, 300); // set window size frame.setLocationRelativeTo(null); // center window frame.setVisible(true); // show window
In this example, a new JFrame
object is created with the title "My Window". The window size is set using the setSize
method, and the window is then centered using the setLocationRelativeTo
method with a null
argument. Finally, the window is made visible using the setVisible
method.
The setLocationRelativeTo
method takes a component as an argument and positions the window relative to it. If the argument is null
, the window is centered on the screen.
You can also use the Dimension
and Toolkit
classes to center the window based on the screen size:
JFrame frame = new JFrame("My Window"); frame.setSize(400, 300); // set window size // get screen size and center window Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int x = (screenSize.width - frame.getWidth()) / 2; int y = (screenSize.height - frame.getHeight()) / 2; frame.setLocation(x, y); frame.setVisible(true); // show window
In this example, the screen size is obtained using the getScreenSize
method of the Toolkit
class. The x and y coordinates for the window are calculated by subtracting the window size from the screen size and dividing by 2. The window is then positioned at the calculated coordinates using the setLocation
method.
These examples will center the window on the screen when it is made visible.