237

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.

spongebob
  • 8,370
  • 15
  • 50
  • 83
AmateurProgrammer
  • 2,609
  • 3
  • 19
  • 14

12 Answers12

588

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);
Tot Zam
  • 8,406
  • 10
  • 51
  • 76
JRL
  • 76,767
  • 18
  • 98
  • 146
  • 109
    +1 if pack() method is used, `setLocationRelativeTo` should be used after pack() method call – Ravindra Gullapalli Aug 09 '12 at 13:26
  • 6
    @Imray because probably it does not work with dual monitor configuration. :P – Ankit Mar 01 '13 at 21:37
  • 18
    It looks like that method should be called after `.setSize()`. – Kamil Jun 30 '13 at 01:22
  • 6
    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. – Paul Gregoire Feb 12 '14 at 01:12
  • 2
    @Ankit it works perfectly with my dual monitor setup. The "best" answer is always chosen by the OP. – Kent May 12 '14 at 20:02
  • 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. – Erick Robertson Oct 09 '15 at 14:53
  • i dont use pack, but i use that before calling setVisible() -> works :D – gumuruh Jan 30 '17 at 22:45
  • this should be the accepted answer, unless someone comes up with one that includes dealing with multi-monitor situations – Menasheh Jan 28 '18 at 12:34
  • pay attention to the order – Jamaluddin Rumi Mar 31 '18 at 00:40
  • 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. – Fom Nov 21 '20 at 17:59
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.

Jack
  • 131,802
  • 30
  • 241
  • 343
  • 1
    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. – 2xedo May 12 '15 at 00:59
  • 16
    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. – Rangi Keen Jun 09 '15 at 15:34
  • 2
    Keep in mind that you must set the JFrame visible BEFORE you center it. – Hunter S Jul 25 '15 at 21:08
  • 5
    @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. – Erick Robertson Oct 09 '15 at 14:51
66

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

Greg
  • 1,189
  • 2
  • 8
  • 14
37

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

enter image description here

Henk van Boeijen
  • 7,357
  • 6
  • 32
  • 42
  • i never thought about this. Anyway, how about the code that work behind itself after we clicked this....? @HenkVanBoeijen – gumuruh Jan 30 '17 at 22:44
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.

Vogel612
  • 5,620
  • 5
  • 48
  • 73
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'.

Asaf Magen
  • 862
  • 10
  • 22
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.

Gstuntz
  • 434
  • 4
  • 10
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.

Kingsley Ijike
  • 1,389
  • 1
  • 8
  • 13
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);

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

K V Ramana
  • 11
  • 1
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);
Mystical
  • 2,505
  • 2
  • 24
  • 43
The Appsolit
  • 89
  • 10
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. ^
Fabik
  • 1
  • 1