To center a window in Java, you can use the setLocationRelativeTo
method of the JFrame
class. This method positions the window relative to a reference component, which can be null
to center the window on the screen.
Here's an example of how you might use the setLocationRelativeTo
method to center a window in Java:
import javax.swing.JFrame; public class Main { public static void main(String[] args) { JFrame frame = new JFrame(); frame.setSize(400, 300); frame.setLocationRelativeTo(null); frame.setVisible(true); } }Sowww:ecru.lautturi.com
This code creates a new window with a size of 400x300 pixels and centers it on the screen by calling the setLocationRelativeTo
method with a null
argument.