开发者

Swing: How to position JFrame N pixels away from the center of the screen at first setVisible()?

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)?


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().


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()


Simple just set:

FormName.setLocation(X-Axis Coordinate, Y-Axis Coordinate);


Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension windowSize = window.getSize();
int windowX = Math.max(0, (screenSize.width  - windowSize.width ) / 2);
int windowY = Math.max(0, (screenSize.height - windowSize.height) / 2);
f.setLocation(windowX, windowY);  // Don't use "f." inside constructor.

                                   OR

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
f.setSize(screenSize.width - 4, screenSize.height - 4);
f.validate();                // Make sure layout is ok
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜