What's the easiest way to centre a java.awt.Window
, such as a JFrame
or a JDialog
?

- 11,218
- 4
- 45
- 56

- 13,427
- 22
- 69
- 98
-
4The title should be "in Swing" not "in Java", it would be more clear that way. – Joe Skora Sep 28 '08 at 01:06
-
7@Joe `setLocation()`, `setLocationRelativeTo()` and `setLocationByPlatform()` or all AWT, not Swing. ;) – Andrew Thompson Sep 13 '11 at 08:58
20 Answers
From this link
If you are using Java 1.4 or newer, you can use the simple method setLocationRelativeTo(null) on the dialog box, frame, or window to center it.

- 633
- 1
- 7
- 18

- 13,427
- 22
- 69
- 98
-
15As @kleopatra said on another answer, setLocationRelativeTo(null) has to be called after pack() in order to work. – Eusebius Apr 19 '14 at 05:18
-
8As explained below, setLocationRelativeTo(null) has to be called after any call of pack() or setSize(). – Arnaud P May 13 '14 at 10:11
-
3@Eusebius Odd, I followed a tutorial that made me set it before `pack()` and it put the topleft corner of the frame at the center of my screen. After moving the line to below `pack()` it got properly centered. – user1433479 Jul 06 '14 at 20:52
-
4Well pack() sets the correct size based on the contents and layout, and you can't centre something unless you know its size, so it is indeed odd that the tutorial had you packing it after centering it. – Andrew Swan Jul 07 '14 at 00:09
-
This should work in all versions of Java
public static void centreWindow(Window frame) {
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
frame.setLocation(x, y);
}

- 185,044
- 174
- 569
- 824
-
I know that this is pretty old but this works fine, provided the frame size is set before calling this function – S.Krishna May 27 '16 at 08:14
-
1
setLocationRelativeTo(null)
should be called after you either use setSize(x,y)
, or use pack()
.

- 6,157
- 8
- 47
- 80

- 871
- 1
- 8
- 16
Note that both the setLocationRelativeTo(null) and Tookit.getDefaultToolkit().getScreenSize() techniques work only for the primary monitor. If you are in a multi-monitor environment, you may need to get information about the specific monitor the window is on before doing this kind of calculation.
Sometimes important, sometimes not...
See GraphicsEnvironment javadocs for more info on how to get this.
On Linux the code
setLocationRelativeTo(null)
Put my window to random location each time I launched it, in a multi display environment. And the code
setLocation((Toolkit.getDefaultToolkit().getScreenSize().width - getSize().width) / 2, (Toolkit.getDefaultToolkit().getScreenSize().height - getSize().height) / 2);
"cut" the window in half with placing it to the exact center, which is between my two displays. I used the following method to center it:
private void setWindowPosition(JFrame window, int screen)
{
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] allDevices = env.getScreenDevices();
int topLeftX, topLeftY, screenX, screenY, windowPosX, windowPosY;
if (screen < allDevices.length && screen > -1)
{
topLeftX = allDevices[screen].getDefaultConfiguration().getBounds().x;
topLeftY = allDevices[screen].getDefaultConfiguration().getBounds().y;
screenX = allDevices[screen].getDefaultConfiguration().getBounds().width;
screenY = allDevices[screen].getDefaultConfiguration().getBounds().height;
}
else
{
topLeftX = allDevices[0].getDefaultConfiguration().getBounds().x;
topLeftY = allDevices[0].getDefaultConfiguration().getBounds().y;
screenX = allDevices[0].getDefaultConfiguration().getBounds().width;
screenY = allDevices[0].getDefaultConfiguration().getBounds().height;
}
windowPosX = ((screenX - window.getWidth()) / 2) + topLeftX;
windowPosY = ((screenY - window.getHeight()) / 2) + topLeftY;
window.setLocation(windowPosX, windowPosY);
}
Makes the window appear right at the center of the first display. This is probably not the easiest solution.
Works properly on Linux, Windows and Mac.

- 4,081
- 10
- 26
- 36

- 1,056
- 2
- 14
- 30
-
Taking multi screen environments into account is the only correct answer, otherwise the screen where the window appears could be somehat random or the window is centered between both screens. – Stephan Dec 24 '15 at 11:15
I finally got this bunch of codes to work in NetBeans using Swing GUI Forms in order to center main jFrame:
package my.SampleUIdemo;
import java.awt.*;
public class classSampleUIdemo extends javax.swing.JFrame {
///
public classSampleUIdemo() {
initComponents();
CenteredFrame(this); // <--- Here ya go.
}
// ...
// void main() and other public method declarations here...
/// modular approach
public void CenteredFrame(javax.swing.JFrame objFrame){
Dimension objDimension = Toolkit.getDefaultToolkit().getScreenSize();
int iCoordX = (objDimension.width - objFrame.getWidth()) / 2;
int iCoordY = (objDimension.height - objFrame.getHeight()) / 2;
objFrame.setLocation(iCoordX, iCoordY);
}
}
OR
package my.SampleUIdemo;
import java.awt.*;
public class classSampleUIdemo extends javax.swing.JFrame {
///
public classSampleUIdemo() {
initComponents();
//------>> Insert your code here to center main jFrame.
Dimension objDimension = Toolkit.getDefaultToolkit().getScreenSize();
int iCoordX = (objDimension.width - this.getWidth()) / 2;
int iCoordY = (objDimension.height - this.getHeight()) / 2;
this.setLocation(iCoordX, iCoordY);
//------>>
}
// ...
// void main() and other public method declarations here...
}
OR
package my.SampleUIdemo;
import java.awt.*;
public class classSampleUIdemo extends javax.swing.JFrame {
///
public classSampleUIdemo() {
initComponents();
this.setLocationRelativeTo(null); // <<--- plain and simple
}
// ...
// void main() and other public method declarations here...
}

- 61
- 1
- 2
below is code for displaying a frame at top-centre of existing window.
public class SwingContainerDemo {
private JFrame mainFrame;
private JPanel controlPanel;
private JLabel msglabel;
Frame.setLayout(new FlowLayout());
mainFrame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
//headerLabel = new JLabel("", JLabel.CENTER);
/* statusLabel = new JLabel("",JLabel.CENTER);
statusLabel.setSize(350,100);
*/ msglabel = new JLabel("Welcome to TutorialsPoint SWING Tutorial.", JLabel.CENTER);
controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
//mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
// mainFrame.add(statusLabel);
mainFrame.setUndecorated(true);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
mainFrame.setVisible(true);
centreWindow(mainFrame);
}
public static void centreWindow(Window frame) {
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
frame.setLocation(x, 0);
}
public void showJFrameDemo(){
/* headerLabel.setText("Container in action: JFrame"); */
final JFrame frame = new JFrame();
frame.setSize(300, 300);
frame.setLayout(new FlowLayout());
frame.add(msglabel);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent windowEvent){
frame.dispose();
}
});
JButton okButton = new JButton("Capture");
okButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// statusLabel.setText("A Frame shown to the user.");
// frame.setVisible(true);
mainFrame.setState(Frame.ICONIFIED);
Robot robot = null;
try {
robot = new Robot();
} catch (AWTException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
final Dimension screenSize = Toolkit.getDefaultToolkit().
getScreenSize();
final BufferedImage screen = robot.createScreenCapture(
new Rectangle(screenSize));
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new ScreenCaptureRectangle(screen);
}
});
mainFrame.setState(Frame.NORMAL);
}
});
controlPanel.add(okButton);
mainFrame.setVisible(true);
} public static void main(String[] args) throws Exception {
new SwingContainerDemo().showJFrameDemo();
}

- 3,351
- 1
- 21
- 17
-
1`frame.setLocation(x, 0);` seems to be wrong - shouldnt it be `frame.setLocation(x, y);` instead? – deem Sep 18 '17 at 21:05
-
x denotes the length of x axis and y denotes the length of y axis. So if you make y=0 then only it should be at top. – Aman Goel Sep 21 '17 at 07:17
-
So `int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);` exists in code only to show that you can also center in vertical axis? Ok, I thought you just forgot to use it, sorry for trouble. – deem Sep 22 '17 at 10:13
-
The following doesn't work for JDK 1.7.0.07:
frame.setLocationRelativeTo(null);
It puts the top left corner at the center - not the same as centering the window. The other one doesn't work either, involving frame.getSize() and dimension.getSize():
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
frame.setLocation(x, y);
The getSize() method is inherited from the Component class, and therefore frame.getSize returns the size of the window as well. Thus subtracting half the vertical and horizontal dimensions from the vertical and horizontal dimensions, to find the x,y coordinates of where to place the top-left corner, gives you the location of the center point, which ends up centering the window as well. However, the first line of the above code is useful, "Dimension...". Just do this to center it:
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
JLabel emptyLabel = new JLabel("");
emptyLabel.setPreferredSize(new Dimension( (int)dimension.getWidth() / 2, (int)dimension.getHeight()/2 ));
frame.getContentPane().add(emptyLabel, BorderLayout.CENTER);
frame.setLocation((int)dimension.getWidth()/4, (int)dimension.getHeight()/4);
The JLabel sets the screen-size. It's in FrameDemo.java available on the java tutorials at the Oracle/Sun site. I set it to half the screen size's height/width. Then, I centered it by placing the top left at 1/4 of the screen size's dimension from the left, and 1/4 of the screen size's dimension from the top. You can use a similar concept.

- 55
- 2
-
1Neither does the other one. These codes put the top left corner of the screen in the center. – Jonathan Caraballo Sep 30 '12 at 05:46
-
7-1 can't reproduce - or more precisely: happens only if the setLocationRelative is called _before_ sizing the frame (by pack or manual setSize). For a zero-sized frame it's top-left corner is the same location as .. its center :-) – kleopatra Dec 02 '12 at 11:41
frame.setLocationRelativeTo(null);
Full example:
public class BorderLayoutPanel {
private JFrame mainFrame;
private JButton btnLeft, btnRight, btnTop, btnBottom, btnCenter;
public BorderLayoutPanel() {
mainFrame = new JFrame("Border Layout Example");
btnLeft = new JButton("LEFT");
btnRight = new JButton("RIGHT");
btnTop = new JButton("TOP");
btnBottom = new JButton("BOTTOM");
btnCenter = new JButton("CENTER");
}
public void SetLayout() {
mainFrame.add(btnTop, BorderLayout.NORTH);
mainFrame.add(btnBottom, BorderLayout.SOUTH);
mainFrame.add(btnLeft, BorderLayout.EAST);
mainFrame.add(btnRight, BorderLayout.WEST);
mainFrame.add(btnCenter, BorderLayout.CENTER);
// mainFrame.setSize(200, 200);
// or
mainFrame.pack();
mainFrame.setVisible(true);
//take up the default look and feel specified by windows themes
mainFrame.setDefaultLookAndFeelDecorated(true);
//make the window startup position be centered
mainFrame.setLocationRelativeTo(null);
mainFrame.setDefaultCloseOperation(mainFrame.EXIT_ON_CLOSE);
}
}

- 4,081
- 10
- 26
- 36

- 3,402
- 30
- 33
There's something really simple that you might be overlooking after trying to center the window using either setLocationRelativeTo(null)
or setLocation(x,y)
and it ends up being a little off center.
Make sure that you use either one of these methods after calling pack()
because the you'll end up using the dimensions of the window itself to calculate where to place it on screen. Until pack()
is called, the dimensions aren't what you'd think thus throwing off the calculations to center the window. Hope this helps.

- 4,960
- 2
- 37
- 45
Example: Inside myWindow() on line 3 is the code you need to set the window in the center of the screen.
JFrame window;
public myWindow() {
window = new JFrame();
window.setSize(1200,800);
window.setLocationRelativeTo(null); // this line set the window in the center of thr screen
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.getContentPane().setBackground(Color.BLACK);
window.setLayout(null); // disable the default layout to use custom one.
window.setVisible(true); // to show the window on the screen.
}

- 41
- 5
The order of the calls is important:
first -
pack();
second -
setLocationRelativeTo(null);

- 1,308
- 13
- 21
The following code center the Window
in the center of the current monitor (ie where the mouse pointer is located).
public static final void centerWindow(final Window window) {
GraphicsDevice screen = MouseInfo.getPointerInfo().getDevice();
Rectangle r = screen.getDefaultConfiguration().getBounds();
int x = (r.width - window.getWidth()) / 2 + r.x;
int y = (r.height - window.getHeight()) / 2 + r.y;
window.setLocation(x, y);
}

- 1,278
- 12
- 26
You could try this also.
Frame frame = new Frame("Centered Frame");
Dimension dimemsion = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dimemsion.width/2-frame.getSize().width/2, dimemsion.height/2-frame.getSize().height/2);

- 4,081
- 10
- 26
- 36

- 3,521
- 1
- 17
- 27
Actually frame.getHeight()
and getwidth()
doesnt return values , check it by System.out.println(frame.getHeight());
directly put the values for width and height ,then it will work fine in center. eg: as below
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x=(int)((dimension.getWidth() - 450)/2);
int y=(int)((dimension.getHeight() - 450)/2);
jf.setLocation(x, y);
both 450 is my frame width n height

- 51,061
- 28
- 99
- 211

- 9,945
- 1
- 40
- 64
-
1-1 a frame's size is zero before ... sizing it :-) Preferably by pack, or at least by manually setting its size to anything else than zero _before_ calling setLocationRelative will allow its internal correct calculation – kleopatra Dec 02 '12 at 11:43
public class SwingExample implements Runnable {
@Override
public void run() {
// Create the window
final JFrame f = new JFrame("Hello, World!");
SwingExample.centerWindow(f);
f.setPreferredSize(new Dimension(500, 250));
f.setMaximumSize(new Dimension(10000, 200));
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void centerWindow(JFrame frame) {
Insets insets = frame.getInsets();
frame.setSize(new Dimension(insets.left + insets.right + 500, insets.top + insets.bottom + 250));
frame.setVisible(true);
frame.setResizable(false);
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
frame.setLocation(x, y);
}
}

- 4,081
- 10
- 26
- 36

- 3,533
- 16
- 44
- 45
In addition to Donal's answer, I would like to add a small calculation that makes sure that the Java window is perfectly at the center of the window. Not just the "TOP LEFT" of the window is at the center of the window
.
public static void centreWindow(JFrame frame, int width, int height) {
Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
int x = (int) ((dimension.getWidth() - frame.getWidth()) / 2);
int y = (int) ((dimension.getHeight() - frame.getHeight()) / 2);
// calculate perfect center
int perf_x = (int) x - width/2;
int perf_y = (int) y - height/2;
frame.setLocation(perf_x, perf_y);
}

- 555
- 7
- 19
If you want a simple answer for Java NetBeans:
Right click on the JFrame, go to properties, then go to code and select generate center option.
Look image for reference: [1]: https://i.stack.imgur.com/RFXbL.png

- 1
If you want to push center of your app window, you can do solved to follow.
int x = (Toolkit.getDefaultToolkit().getScreenSize().width) - getSize().width) / 2;
int y = (Toolkit.getDefaultToolkit().getScreenSize().height) - getSize().height) / 2;
setLocation(x,y);
getSize() function is app frame size... getScreenSize() is your pc screen size.

- 1
- 1
I'd like to modify Dónal's answer to accommodate a multiple display setup:
public static void centerWindow(Window frame) {
Rectangle bounds = frame.getGraphicsConfiguration().getBounds();
Dimension dimension = bounds.getSize();
int x = (int) (((dimension.getWidth() - frame.getWidth()) / 2) + bounds.getMinX());
int y = (int) (((dimension.getHeight() - frame.getHeight()) / 2) + bounds.getMinY());
frame.setLocation(x, y);
}

- 2,749
- 3
- 21
- 42