JFrame
Center JFrame/JWindow/JDialog on screen
In this example we shall show you how to center JFrame
, JWindow
, JDialog
components in a Java Desktop Application. You can use this when you want to center you windows in your application automatically. For example, if your application has to handle many windows, you might want to add a button that centers the components you want.
Basically, all you have to do to center a JFrame
, JWindow
, JDialog
on the screen is:
- Create a
JFrame
. - Call
Toolkit.getDefaultToolkit().getScreenSize()
to get the screen dimensions. This will return aDimension
object representing the screen dimensions. - Use
JFrame.getSize().width
,JFrame.getSize().height
methods to get the coordinates of the window. - Then calculate the new coordinates of the window as you will see in the code snippet, and call
JFrame.setLocation(x, y)
to set the new location of the window.
Let’s see the code:
package com.javacodegeeks.snippets.desktop; import java.awt.Dimension; import java.awt.Toolkit; import javax.swing.JFrame; public class CenterJFrameJWindowJDialogOnScreen { private static final long serialVersionUID = 1L; private static void createAndShowGUI() { // Create and set up the window. JFrame frame = new JFrame("Centered"); // Display the window. frame.setSize(300, 300); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); center(frame); } public static void center(JFrame frame) { // get the size of the screen, on systems with multiple displays, // the primary display is used Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // calculate the new location of the window int w = frame.getSize().width; int h = frame.getSize().height; int x = (dim.width - w) / 2; int y = (dim.height - h) / 2; // moves this component to a new location, the top-left corner of // the new location is specified by the x and y // parameters in the coordinate space of this component's parent frame.setLocation(x, y); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application's GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }
This was an example on how to center a JFrame/JWindow/JDialog on screen in a Java Desktop Application.