tags:

views:

524

answers:

2

What's the code to position a JFrame N pixels (say 300 pixels in x-direction) away from the center of the screen before one calls setVisible(true)?

+2  A: 

Some info provide by the Frame Javadoc, could help you to set location of your JFrame before the call setVisible(true) with the setLocation() method

You can get the center point of the screen by calling GraphicsEnvironment.getCenterPoint()

Nettogrof
+3  A: 

I typically do something like the following to center a JFrame. You can add the offset to the wdwLeft variable as shown in the listing to move the frame off center. (The call to setPreferredSize() is superfluous and only there to make this demo work.)

package testapplication;

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Toolkit;
import javax.swing.JFrame;

public class MyJFrame extends JFrame {

    MyJFrame() {
        super("Test");
        Dimension screenSize = new Dimension(Toolkit.getDefaultToolkit().getScreenSize());
        setPreferredSize(new Dimension(200, 200));
        Dimension windowSize = new Dimension(getPreferredSize());
        int wdwLeft = 300 + screenSize.width / 2 - windowSize.width / 2;
        int wdwTop = screenSize.height / 2 - windowSize.height / 2;
        pack();   
        setLocation(wdwLeft, wdwTop);
    }

    public static void main(final String [] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                final MyJFrame jf = new MyJFrame();
                jf.setVisible(true);
            }
        }
       );
    }
 }

You can add additional logic to assure that the offset window is still completely within the screen as determined by getMaximumWindowBounds().

clartaq
I think you should pack first, then call setLocation, using frame.getSize().
Steve McLeod
yes, must pack first then do setlocation
Suraj Chandran
Thanks. I've made the change.
clartaq