Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swing

jframe

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

like image 865
sivabudh Avatar asked Dec 18 '22 04:12

sivabudh


1 Answers

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

like image 125
clartaq Avatar answered Jan 31 '23 10:01

clartaq