How to set JFrame to appear centered, regardless of monitor resolution?
Asked Answered
I

12

235

While working with Java, I find it hard to position my main window in the center of the screen when I start the application.

Is there any way I can do that? It doesn't have to be vertically centered, horizontal alignment is the more important goal for me. But vertical alignment is also welcome.

Isoprene answered 14/3, 2010 at 15:18 Comment(0)
A
260

I always did it in this way:

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);

where this is the JFrame involved.

Alburga answered 14/3, 2010 at 15:22 Comment(4)
I know this answer is really old but is there any possible way to do this in a static context? I'm deciding between working towards that or just dropping the public static void main(String[] args) that I for whatever reason wanted to use.Unworldly
This will work in a single monitor setup, but with dual monitors it may appear straddling the two (assuming they are the same resolution). Using setLocationRelativeTo(null) will center it on the primary monitor even in a multi-monitor setup.Vicegerent
Keep in mind that you must set the JFrame visible BEFORE you center it.Charcuterie
@HunterS : this is incorrect. In fact, it is recommended to not set it visible until AFTER you center it. This way it won't appear and then jump around. As long as you have packed the frame or set the dimensions before the code in this answer, you will be fine.Drudgery
A
592

Use setLocationRelativeTo(null)

This method has a special effect when you pass it a null. According to the Javadoc:

If the component is null, or the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen.

This should be done after setting the size or calling pack(), but before setting it visible, like this:

frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
Apelles answered 14/3, 2010 at 15:24 Comment(10)
+1 if pack() method is used, setLocationRelativeTo should be used after pack() method callChadbourne
@Imray because probably it does not work with dual monitor configuration. :PMagocsi
It looks like that method should be called after .setSize().Cata
This works in a multi-monitor setup and as stated in the comments it must be called after pack() and setSize() if they are called at all.Bargainbasement
@Magocsi it works perfectly with my dual monitor setup. The "best" answer is always chosen by the OP.Carminecarmita
If you have your dual monitors configured as one monitor, then this may center across both monitors. This is not Java's fault as you have configured it as one monitor so that's what it's doing. For example, if you are playing games and spanning the screen across multiple monitors, you may have a setup like this in your video card software.Drudgery
i dont use pack, but i use that before calling setVisible() -> works :DLugger
this should be the accepted answer, unless someone comes up with one that includes dealing with multi-monitor situationsUnderset
pay attention to the orderSulfatize
Worth pointing out: If you put setLocationRelativeTo(null) before pack() rather than after (as many comments have advised), your JFrame will have its upper left corner centered.Parochial
A
260

I always did it in this way:

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);

where this is the JFrame involved.

Alburga answered 14/3, 2010 at 15:22 Comment(4)
I know this answer is really old but is there any possible way to do this in a static context? I'm deciding between working towards that or just dropping the public static void main(String[] args) that I for whatever reason wanted to use.Unworldly
This will work in a single monitor setup, but with dual monitors it may appear straddling the two (assuming they are the same resolution). Using setLocationRelativeTo(null) will center it on the primary monitor even in a multi-monitor setup.Vicegerent
Keep in mind that you must set the JFrame visible BEFORE you center it.Charcuterie
@HunterS : this is incorrect. In fact, it is recommended to not set it visible until AFTER you center it. This way it won't appear and then jump around. As long as you have packed the frame or set the dimensions before the code in this answer, you will be fine.Drudgery
F
68

You can call JFrame.setLocationRelativeTo(null) to center the window. Make sure to put this before JFrame.setVisible(true)

Futurism answered 14/3, 2010 at 15:24 Comment(1)
+1 if pack() method is used, setLocationRelativeTo should be used after pack() method callChadbourne
U
38

Just click on form and go to JFrame properties, then Code tab and check Generate Center.

enter image description here

Uranic answered 28/1, 2016 at 3:54 Comment(1)
i never thought about this. Anyway, how about the code that work behind itself after we clicked this....? @HenkVanBoeijenLugger
K
14

As simple as this...

setSize(220, 400);
setLocationRelativeTo(null);  

or if you are using a frame then set the frame to

frame.setSize(220, 400);
frame.setLocationRelativeTo(null);  

For clarification, from the docs:

If the component is null, or the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen.

Kathernkatheryn answered 15/12, 2014 at 15:20 Comment(0)
C
7

i am using NetBeans IDE 7.2.1 as my developer environmental and there you have an option to configure the JForm properties.

in the JForm Properties go to the 'Code' tab and configure the 'Generate Center'. you will need first to set the Form Size Policy to 'Generate Resize Code'.

Carborundum answered 21/2, 2013 at 11:16 Comment(0)
G
7

I am using NetBeans IDE 7.3 and this is how I go about centralizing my JFrame Make sure you click on the JFrame Panel and go to your JFrame property bar,click on the Code bar and select Generate Center check box.

Gert answered 13/6, 2013 at 7:30 Comment(0)
K
2

If you use NetBeans, simply click on the frame on the design view, then the code tab on its properties. Next, check 'Generate Center'. That will get the job done.

Keef answered 31/3, 2015 at 14:16 Comment(0)
M
1

If you explicitly setPreferredSize(new Dimension(X, Y)); then it is better to use:

setLocation(dim.width/2-this.getPreferredSize().width/2, dim.height/2-this.getPreferredSize().height/2);

Megaphone answered 5/12, 2016 at 11:31 Comment(0)
F
1

In Net Beans GUI - go to jframe (right click on jFrame in Navigator) properties, under code, form size policy property select Generate Resize Code. In the same window, Untick Generate Position and tick Generate Size and Center.

Enjoy programming. Ramana

Flashy answered 22/1, 2019 at 8:47 Comment(0)
C
0

You can use this method, which allows the JFrame to be centered and full screen at the same time.

yourframe.setExtendedState(JFrame.MAXIMIZED_BOTH);
Cincinnatus answered 16/3, 2016 at 2:22 Comment(0)
J
0

I will provide 3 methods to your question :

You can either use the simplest method to center it, relative to your viewport, which is :

setLocationRelativeTo(null);

The second one, is to use :

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); frame.setLocation(dim.width/2 - frame.getSize().width/2, dim.height/2 - frame.getSize().height/2);

And the third one, the most customizable one, is a bit more complicated, but is the most useful. (in my opinion) :

1.) You create a JButton and add it to your panel.

2.) You add an ActionListener event to it.

3.) On your button click, you invoke the method :

frame.getLocationOnScreen(); which you need to save to a Point variable => Point location = frame.getLocationOnScreen;

4.) After that, you invoke : System.out.println(location);, so that you can get the location on the screen that you want to put your frame to - it will print it to the console.

5.) You delete the button and ActionListener, after you've got the x, y coordinates.

6.) You invoke : frame.setLocation(x, y);

  • That's it.

The code looks like this :

JButton button = new JButton();
    button.setText("Get Location");
    panel.add(button);
    
    ActionListener onButton = new ActionListener() {
        
        @Override
        public void actionPerformed(ActionEvent e) {
            
            Point location = frame.getLocationOnScreen();
            System.out.println(location);
            
        }
        
    };
    
    button.addActionListener(onButton);

After you have the location, do this :

frame.setLocation(445, 195);
  • Hope I was helpful. ^
Jer answered 13/2, 2023 at 18:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.