63

I'm a .Net developer but somehow I was task to create a simple application in java for some extra reason. I was able to create that application but my problem is how can i center the form in the screen when the application is launched?

Here is my code:

private void formWindowActivated(java.awt.event.WindowEvent evt) 
{
        // Get the size of the screen
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();

        // Determine the new location of the window
        int w = this.getSize().width;
        int h = this.getSize().height;
        int x = (dim.width-w)/2;
        int y = (dim.height-h)/2;

        // Move the window
        this.setLocation(x, y);
}

The code above works fine but the problem is I've seen the form moving from the topleft most to center screen. I also tried adding that code in formWindowOpened event and still shows same action. Is there a better way for this? Just like in .NET Application there is a CenterScreen Position. Or if the code above is correct, on what Event will i put it?

Thanks for reading this.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
John Woo
  • 258,903
  • 69
  • 498
  • 492
  • What are you using? JFrame? If so, before you set visibility to true, try to set the location first. – kazinix Mar 03 '12 at 04:04
  • I smell Pinoy here. For reference of JFrame http://docs.oracle.com/javase/1.4.2/docs/api/javax/swing/JFrame.html. For it's superclass Frame http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/Frame.html. For Frame's superclass, Window http://docs.oracle.com/javase/1.4.2/docs/api/java/awt/Window.html... On the last link, you'll see the property setter inherited by the JFrame from Window class, setLocationRelativeTo. – kazinix Mar 03 '12 at 04:19

9 Answers9

138

Simply set location relative to null after calling pack on the JFrame, that's it.

e.g.,

  JFrame frame = new JFrame("FooRendererTest");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.getContentPane().add(mainPanel); // or whatever...
  frame.pack();
  frame.setLocationRelativeTo(null);  // *** this will center your app ***
  frame.setVisible(true);
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 1
    Sir if you mind, where will I put this code? I'm sorry if i ask this noobish thing because I am not very familiar with the environment. – John Woo Mar 03 '12 at 04:10
  • @johntotetwoo Put it where you are initializing your JFrame. What IDE do you use? Did you let the IDE create the window automatically for you? If so, find the initialization of JFrame (new Jframe)... – kazinix Mar 03 '12 at 04:13
  • I'm using NetBeans 7.1 sir. I'll check the initializing code. – John Woo Mar 03 '12 at 04:15
  • Doesn't this set the top-left corner at the center of your screen, rather than centering the whole frame? – Xynariz Nov 19 '13 at 21:53
  • 2
    @Xynariz: no, not if you call `pack()` first before `setLocationrelativeTo(null)`, but you could have answered that yourself with a small test program. In fact -- why don't you check it out? – Hovercraft Full Of Eels Nov 19 '13 at 22:36
  • I have tried - it seems to be system dependent. But thanks for the prompt answer anyways. – Xynariz Nov 20 '13 at 20:19
  • call setLocationrelativeTo(null) after other configuration methods. – resw67 Jan 23 '17 at 19:52
  • Keep in mind that setLocationrelativeTo(null) will center it on the primary screen, which may not necessarily be the screen you want, if the system has multiple screens. – Asu Jun 21 '18 at 17:18
12

The following example centers a frame on the screen:

package com.zetcode;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GraphicsEnvironment;
import java.awt.Point;
import javax.swing.JFrame;


public class CenterOnScreen extends JFrame {

    public CenterOnScreen() {

        initUI();
    }

    private void initUI() {

        setSize(250, 200);
        centerFrame();
        setTitle("Center");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private void centerFrame() {

            Dimension windowSize = getSize();
            GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
            Point centerPoint = ge.getCenterPoint();

            int dx = centerPoint.x - windowSize.width / 2;
            int dy = centerPoint.y - windowSize.height / 2;    
            setLocation(dx, dy);
    }


    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                CenterOnScreen ex = new CenterOnScreen();
                ex.setVisible(true);
            }
        });       
    }
}

In order to center a frame on a screen, we need to get the local graphics environment. From this environment, we determine the center point. In conjunction with the frame size, we manage to center the frame. The setLocation() is the method that moves the frame to the central position.

Note that this is actually what the setLocationRelativeTo(null) does:

public void setLocationRelativeTo(Component c) {
    // target location
    int dx = 0, dy = 0;
    // target GC
    GraphicsConfiguration gc = getGraphicsConfiguration_NoClientCode();
    Rectangle gcBounds = gc.getBounds();

    Dimension windowSize = getSize();

    // search a top-level of c
    Window componentWindow = SunToolkit.getContainingWindow(c);
    if ((c == null) || (componentWindow == null)) {
        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        gc = ge.getDefaultScreenDevice().getDefaultConfiguration();
        gcBounds = gc.getBounds();
        Point centerPoint = ge.getCenterPoint();
        dx = centerPoint.x - windowSize.width / 2;
        dy = centerPoint.y - windowSize.height / 2;
    }

  ...

  setLocation(dx, dy);
}
Jan Bodnar
  • 10,969
  • 6
  • 68
  • 77
  • `GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); Point centerPoint = ge.getCenterPoint(); int dx = centerPoint.x - windowSize.width / 2; int dy = centerPoint.y - windowSize.height / 2; setLocation(dx, dy);` LOL! `setLocationRelativeTo(null);` is a lot shorter. – Andrew Thompson Aug 31 '16 at 13:57
  • This should be the accepted cause contains an explanation – exploitr Jun 13 '18 at 06:48
5

Change this:

public FrameForm() { 
    initComponents(); 
}

to this:

public FrameForm() {
    initComponents();
    this.setLocationRelativeTo(null);
}
Nick Volynkin
  • 14,023
  • 6
  • 43
  • 67
mesutpiskin
  • 1,771
  • 2
  • 26
  • 30
  • Edited formatting in your answer. But it's still unclear what this does and why it is a solution. Please edit and explain. – Nick Volynkin Jun 24 '15 at 10:59
2
public class Example extends JFrame {

public static final int WIDTH = 550;//Any Size
public static final int HEIGHT = 335;//Any Size

public Example(){

      init();

}

private void init() {

    try {
        UIManager
                .setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");

        SwingUtilities.updateComponentTreeUI(this);
        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
        setSize(WIDTH, HEIGHT);

        setLocation((int) (dimension.getWidth() / 2 - WIDTH / 2),
                (int) (dimension.getHeight() / 2 - HEIGHT / 2));


    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (UnsupportedLookAndFeelException e) {
        e.printStackTrace();
    }

}
}
1

If you use NetBeans IDE right click form then

Properties ->Code -> check out Generate Center

codelover
  • 131
  • 1
  • 10
0

i hope this will be helpful.

put this on the top of source code :

import java.awt.Toolkit;

and then write this code :

private void formWindowOpened(java.awt.event.WindowEvent evt) {                                  
    int lebar = this.getWidth()/2;
    int tinggi = this.getHeight()/2;
    int x = (Toolkit.getDefaultToolkit().getScreenSize().width/2)-lebar;
    int y = (Toolkit.getDefaultToolkit().getScreenSize().height/2)-tinggi;
    this.setLocation(x, y);
}

good luck :)

0

Actually, you dont really have to code to make the form get to centerscreen.

Just modify the properties of the jframe
Follow below steps to modify:

  • right click on the form
  • change FormSize policy to - generate resize code
  • then edit the form position X -200 Y- 200

You're done. Why take the pain of coding. :)

jfalexvijay
  • 3,681
  • 7
  • 42
  • 68
  • What if someone isn't really performing a drag and drop approach. How will you consider your answer than? – Jamshaid Feb 23 '20 at 16:14
-3

Try using this:

this.setBounds(x,y,w,h);
Mifeet
  • 12,949
  • 5
  • 60
  • 108
-3

Using this Function u can define your won position

setBounds(500, 200, 647, 418);
Prasad V S
  • 262
  • 4
  • 17